Month: September 2014

OAuth process in a Jaggery Application

Introduction

JaggeryJS can be introduced as a “a framework to write webapps and HTTP-focused web services for all aspects of the application: front-end, communication, Server-side logic and persistence in pure Javascript” [1]. Many web applications will not be a standalone ones, instead they tend to exchange data with available online services. The first step of accessing an external services is authorizing. Many external service providers do recommend to use libraries written to access their services. But for JaggeryJS you won’t find such things. Therefore in this article I’m going to show you how to complete authorizing part of connecting to external service.

For this example I’m using Twitter as the external service. Additionally I assume that you have basic knowledge in creating a Jaggery Application. At the end of this process you will receive an Access Token and an Access Secret, which authorize you to call Twitter API methods.

OAuth process

For this example, I’ve selected Twitter OAuth 1.0a process. The data-flow diagram of the overall process can be seen as follows.

twitter-oauth-flow

As depicts in the diagram flow can be mainly categorized in to 3 sections:
1. Obtain Request Token
2. User authorizes Request Token
3. Exchange Request Token for Access Token
The same process can take variety of ways and different Service Providers may require different parameters in requests. OAuth 2.0 also closely follow this flow but can be differ depending on the Service Provider.

Registering App

As the first step, you need to register the app you wish to create. At their you need to mention what things you are going to do and app related details.
1. Login to Twitter account
2. Go to the Twitter applications page at https://dev.twitter.com/apps and click Create a new application.
3. Fill the application related details and make a note of “Consumer Key (API Key)” and “Consumer Secret (API Secret)” under “Keys and Access Tokens” tab.

twitter_app

4. Add twitter certificate to client-truststore.jks. For this you need to go to ‘ https://api.twitter.com/oauth2/token ‘ and save the certificate. Then execute the following keytool command :

 keytool -importcert -file <certificate file> -keystore <JaggeryLocation>/repository/resources/security/client-truststore.jks -alias "TwitterTrustCertImport"

(This is only require once to avoid from error: SSLHandshakeException – unable to find valid certification path to requested target )

Now you are done with the first step!

Creating the Jaggery Application

According to the assumption I made, basic steps of creating a Jaggery app is omitted here. Also for this I’m using “oauth.jag” file which can be accessed via ‘ http://127.0.0.1/myapp/oauth ‘ (Hint: should be done via jaggery.conf file). Code resides in oauth.jag file can be divided into sections as follows.


// To use oauth module in Jaggery
var oauth = require('oauth');

// To log content
var log = new Log();

// Config object for OAuthProvider
var configs = {
	'oauth_version'     : '1',
	'authorization_url' : 'https://api.twitter.com/oauth/authorize',
	'access_token_url'  : 'https://api.twitter.com/oauth/access_token',
	'request_token_url' : 'https://api.twitter.com/oauth/request_token',
	'api_key'           : 'YOUR_API_KEY',
	'api_secret'        : 'YOUR_API_SECRET',
	'callback_url'	    : 'http://127.0.0.1/myapp/oauth'
};

// The request coming to the page check for parameter 'oauth_verifier' (this name can be vary depending on Service Provider)
// If not, consider it as to get a new Access Token - inside if block
// If it presents, consider it as the request coming after getting user authorizing - inside else block
if(!request.getParameter('oauth_verifier')) {

        // Create a new OAuthProvider using the config
	var oauthService = new oauth.OAuthProvider(configs);

        // Get Authorizing url (Obtaining Request Token is automatically handled by inside)
	var authUrl = oauthService.getAuthorizationUrl();

        // Put 'oauthService' object in to session as a preparation for redirection
	session.put('oauth_service', oauthService);

        // Redirect to authorize url, so that user now gets a button to Authorize the app
	response.sendRedirect(authUrl);

}
else{

        // Take-out the 'oauthService' object saved in the session
	var oauthService = session.get('oauth_service');

        // Take the 'oauth_verifier' parameter from the request received
	var verifier = request.getParameter('oauth_verifier');

        // Exchange the user authorized Request Token for Access Token, also need to send verifier too
	var auth_token = oauthService.getAccessToken(verifier);

	// Log token received
 	log.info('Token  : ' + auth_token.token);
 	log.info('Secret : ' + auth_token.secret);

        // Additionally, calling verify_credentials using the received Access Token and Access Secret
	var twitterresponse = oauthService.sendOAuthRequest(auth_token, 'GET', 'https://api.twitter.com/1/account/verify_credentials.json');

}

Special Note

The above example is not the same mentioned in the JaggeryJS documentation [2]. As you can see, there’s an additional property ‘callback_url’ is added to config object. This helps you to avoid Out-Of-Band (oob), which is the default way of authorizing. However for this is not supported by the current released version of JaggeryJS and, you need to patch oauth plugin with the PR : https://github.com/wso2/jaggery-extensions/pull/9 .
By removing ‘callback_url’, you can switch to oob mode. But you need to find some method to send Access Token request along with the pin number you get.
Also you should be aware that when calling-back to oauth.jag, you should not violate ip address. Otherwise you will not be able to get ‘oauthService’ object which get stored in the session.

Special thanks goes to WSO2 ES team for helping to overcome issues faced.

References

[1] Jaggery documentation – http://jaggeryjs.org/documentation.jag
[2] OAuth in Jaggery – http://jaggeryjs.org/documentation.jag?api=oauth
[3] Twitter Developer Documentation – https://dev.twitter.com/overview/documentation

Advertisements

Modify XML using Jaggery

Jaggery E4X

Introduction

JaggeryJS is an opensource project which is developed and maintain by WSO2. It is to “offer a completely Javascript way to write all parts of Web applications and services as a way to reduce/eliminate impedance mismatches across different layers of the Web application and API development experience.”

Problem facing

In cases when you are writing server-side codes, you may need to manipulate XML files. During such situations you may find difficulties in doing it since Jaggery documentation doesn’t contain sufficient information on that. In this article I’m going to mention on how to achieve some XML related manipulations based on the experience I got.

Sample XML

For the purpose of explanation I’ll use the following XML document in the rest of this article.


<task name="Task1" xmlns="http://www.wso2.org/products/wso2commons/tasks">
  <trigger count="1" interval="100"/>
  <property xmlns:task="http://www.wso2.org/products/wso2commons/tasks" name="Params">
    <salesforceInfo xmlns="">
      <salesforce.username>buddhima</salesforce.username>
      <salesforce.batchSize>20</salesforce.batchSize>
    </salesforceInfo>
  </property>
</task>

Reading from a file

Let’s assume the XML content is in a file called “task.xml”. So initially you need to read from there and form an XML object out of it.


var file = new File("task.xml");

// Here open file just to read
file.open("r");

// Read task xml file and convert to xml object
var taskFile = file.readAll();
var taskFileXml = new XML(taskFile);

// Close the file
file.close();

// Any thing you want to do with taskFileXml object goes here ...

From here onwards I consider “taskFileXml” is an object with the XML given in Sample XML.

Changing a value inside XML tags

If you want to change content inside “salesforce.username”, you can do it as follows:


taskFileXml..*::['salesforce.username'].setChildren('new_username_here');

Note that ‘..*::’ notation will find out the first XML element contains ‘salesforce.username’ for you.

Changing attribute of the <task>

Following code will change the name attribute inside task element.


taskFileXml.@name='new_name';

Changing attributes inside <task>

To change the ‘interval’ attribute of you can use the following:


taskFileXml..*::['trigger'].@interval='555';

Saving XML file

To save modified ‘taskFileXml’ object, following code can be used.


var file = new File("newtask.xml");
file.open("w");

// At the end write all the content to newtask xml file
file.write(taskFileXml);
file.close();

Convert XML object to a JSON object

It may be quite handy to use JSON objects rather than XML objects. By engaging ‘util’ module with Jaggery, you can achieve this:


// Translate xml to json using jaggery new util-xml module
var utils = require('utils').xml;
var taskConvertedJson = utils.convertE4XtoJSON(taskFileXml);

Final Note

Most of these operations are extracted from E4X documentation, which is deprecated but using in JaggeryJS. In this article I tried to provide concrete use-cases with XML manipulations and hope will help in your Jaggery App.

References

[1] JaggeryJS Documentation : http://jaggeryjs.org/documentation.jag
[2] Jaggery XML : http://jaggeryjs.org/documentation.jag?api=xml
[3] E4X Quick Start : http://wso2.com/project/mashup/0.2/docs/e4xquickstart.html
[4] E4X Specification : http://www.ecma-international.org/publications/files/ECMA-ST/Ecma-357.pdf