Authenticating users from LinkedIn or Twitter in iOS and Android using Titanium

Posted By : Arpit Sharma | 30-Jul-2012

Here we'll discuss how to authenticate users on your app from linkedIn or Twitter.

First of all download libraries Oauth.js and sha1.js  and put them into lib folder.

We have to follow three steps for authentication.

1. Request token

2. Show the authentication page to authorize the app. and get the pin.

3. Get the access token.

Create oauth_client.js file in which we'll execute above three.

  • Include Oauth.js and sha1.js in oauth_client.js.
Ti.include('lib/sha1.js');
Ti.include('lib/oauth.js');

 

  • Create a function name oauth_client and defined the app keys, rest API's and variables in it. 
var oauth_client = function() {

	// You will get this key and secret when you create the application in LinkedIn or twitter.
	var CONSUMER_KEY = 'xxxxxxxxxx';
	var CONSUMER_SECRET = 'xxxxxxxxxxxxxxxxxxxxxxx';

	// these are the linkedIn REST API
	var REQUEST_TOKEN_URL = 'https://api.linkedin.com/uas/oauth/requestToken';
	var AUTHORIZE_URL = 'https://api.linkedin.com/uas/oauth/authorize';
	var ACCESS_TOKEN_URL = 'https://api.linkedin.com/uas/oauth/accessToken?';
        
       // these are the twitter REST API
	/*var REQUEST_TOKEN_URL = 'https://api.twitter.com/oauth/request_token';
	var AUTHORIZE_URL = 'https://api.twitter.com/oauth/authorize';
	var ACCESS_TOKEN_URL = 'https://api.twitter.com/oauth/access_token';*/
        
       // the accessor is used when communicating with the OAuth libraries to sign the messages
	var accessor = {
		consumerSecret : CONSUMER_SECRET,
		tokenSecret : ''
	};

	var pin = null;
	var oauth_token = null;
	var oauth_token_secret = null;

	//@method get_oauth_token
	this.get_oauth_token = function() {
		return oauth_token;
	};
	
	 //@method get_oauth_token_secret
	this.get_oauth_token_secret = function() {
		return oauth_token_secret;
	};

	 //@method get_pin
	this.get_pin = function() {
		return pin;
	};

	//@method get_pin
	this.set_pin = function(html) {

		// for Twitter
		//var regExp = '(.*?)';

		// for linkedIn
		var regExp = /<div class="access-code">(.*?)<\/div>/;

		var result = RegExp(regExp).exec(html);
		if (result == null || result.length < 2) {
			pin = null;
			Ti.API.debug('Result : ' + result);
			return null;
		}
		pin = result[1];
		return pin;
	}
}


 

  • Now added request_token the 1st step for authentication in oauth_client function.
        /**
	 * 1st step of oAuth.
	 * @method request_token
	 */
	this.request_token = function(complete) {
		var message = {
			action : REQUEST_TOKEN_URL,
			method : 'POST',
			parameters : []
		};

		message.parameters.push(['oauth_consumer_key', CONSUMER_KEY]);
		message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);

		OAuth.setTimestampAndNonce(message);
		OAuth.SignatureMethod.sign(message, accessor);

		var client = Ti.Network.createHTTPClient();
		client.open('POST', REQUEST_TOKEN_URL, true);
		client.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		client.setRequestHeader("Authorization", OAuth.getAuthorizationHeader("", message.parameters));

		client.onload = function() {
			Ti.API.debug('[load]' + this.status);
			var responseParams = OAuth.getParameterMap(client.responseText);

			oauth_token = responseParams['oauth_token'];
			oauth_token_secret = responseParams['oauth_token_secret'];

			if (complete != 'undefined') {
				complete();
			}
		}
		client.send(null);
	};

 

  • Added get_authorize_url_with_token the 2nd step for authentication in oauth_client function.
       /**
	 * 2nd step of oAuth.
	 * @method get_authorize_url_with_token
	 */
        this.get_authorize_url_with_token = function() {
		return AUTHORIZE_URL + '?oauth_token=' + oauth_token;
	};

 

  • Added access_token the 3rd step for authentication in oauth_client function.
        /**
	 * 3rd step of oAuth.
	 * @method access_token
	 */
	this.access_token = function(complete) {
		accessor.tokenSecret = oauth_token_secret;

		var message = {
			action : ACCESS_TOKEN_URL,
			method : 'POST',
			parameters : []
		};
		message.parameters.push(['oauth_consumer_key', CONSUMER_KEY]);
		message.parameters.push(['oauth_token', oauth_token]);
		message.parameters.push(['oauth_signature_method', 'HMAC-SHA1']);
		message.parameters.push(['oauth_verifier', pin]);

		OAuth.setTimestampAndNonce(message);
		OAuth.SignatureMethod.sign(message, accessor);

		var client = Ti.Network.createHTTPClient();

		client.open('POST', ACCESS_TOKEN_URL, true);
		client.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;');
		client.setRequestHeader("Authorization", OAuth.getAuthorizationHeader("", message.parameters));

		client.onload = function() {
			var responseParams = OAuth.getParameterMap(client.responseText);
			oauth_token = responseParams['oauth_token'];
			oauth_token_secret = responseParams['oauth_token_secret'];
			complete.call();
		}
		client.send(null);
	};

 

In app.js file we have to added the following code.

Ti.include('oauth_client.js');

var popup_window = Ti.UI.createWindow({
	backgroundColor : "#fff"
});

//Create the client instance.
var client = new oauth_client();

//Create the label that shows "loading" message so user knows that something is happening.
var loadingLabel = Ti.UI.createLabel({
	text : 'Loading... Please wait.',
});
popup_window.add(loadingLabel);

/**
 * This is the 2nd step of oAuth. It will show the authentication page for you to enter user name and password to authorize the app.
 */
var show_on_webview = function(url, complete) {
	var view = Ti.UI.createView({
		width : "100%",
		height : "100%",
		border : 10,
		backgroundColor : 'white',
		borderColor : '#aaa',
		borderWidth : 5,
	});
	var closeLabel = Ti.UI.createLabel({
		textAlign : 'right',
		font : {
			fontWeight : 'bold',
			fontSize : '8sp'
		},
		text : '(X)',
		top : 10,
		right : 12,
		height : 35
	});
	var webView = Ti.UI.createWebView({
		url : url,
		top : "55dp",
		width : "100%",
		height : "100%",
	});
	view.add(webView);
	webView.addEventListener('beforeload', function(e) {
		if (Ti.Platform.osname == "android")
			view.visible = false;
	});
	webView.addEventListener('load', function(e) {
		var html = e.source.html;
		client.set_pin(html);
		if ((complete != 'undefined') && (client.get_pin() != null)) {
			complete();
		}
		if (Ti.Platform.osname == "android")
			view.visible = false;
	});
	closeLabel.addEventListener('click', function() {
		popup_window.close();
	});
	view.add(closeLabel);
	popup_window.add(view);
	return;
};

/**
 * Save the token, secret and pin in file.
 */
var save_token_and_secret = function() {
	Ti.App.Properties.setString("oauth_token", client.get_oauth_token());
	Ti.App.Properties.setString("oauth_token_secret", client.get_oauth_token_secret());
	Ti.App.Properties.setString("pin", client.get_pin());
	alert("Authentication Complete");
}
/**
 * Save the token, secret and pin in file.
 */
var get_access_token = function() {
	client.access_token(function() {
		save_token_and_secret();
	});
}
var login = function() {
	client.request_token(function() {
		show_on_webview(client.get_authorize_url_with_token(), get_access_token);
	});
}
login();
popup_window.open();

 

Arpit Sharma
[email protected]

http://oodlestechnologies.com/

About Author

Author Image
Arpit Sharma

Arpit has been developing Android and iPhone applications for a while now and is expert in mobile application development . He excels in developing mobile applications with location based intelligence. Arpit loves Modelling as a hobby.

Request for Proposal

Name is required

Comment is required

Sending message..