Update 2 See this post or just skip straight to this excellent library for all of your OAuth and Java needs

*Update* The code in this entry no longer works with the Android SDK because of the upgrade to HttpClient 4. The OAuth Java library has been updated to work with HttpClient 4 but I have not looked at it recently *Update*
Fire eagle is a Yahoo! location sharing service that provides an API that allows external clients and services to update and query user location information. Besides the obvious interesting connection between a location sharing service and Android’s Location-Based-Services API, I became more interested in how fire eagle uses OAuth as it’s authorization scheme and how it can be used on a smart mobile device.

OAuth is an open authentication protocol that allows access to web service resources from other web services as well as desktop applications. Other open authentication schemes, like OpenID, use http redirects and require users input credentials onto a web page in order to authorize clients. This isn’t very useful for a desktop or mobile client that would like direct access to a web API. OAuth still requires the user to enter their credentials into a website, but this is only done during the initial application authorization step, after that step is complete the application can make authorized API calls directly without needing user intervention.

A web service that uses OAuth will let application developers to register for a consumer key which is paired with a consumer secret. The consumer key is used to identify the client application and the consumer secret is used to sign requests made by the client application which is then verified by the host web service.

Here is a general outline of the OAuth process from a client application’s perspective:
1. The client requests a request token from the service. They include their consumer key and a few other OAuth specific parameters including a hash signature using the consumer secret.The service replies with a request token.
2. The client application then directs the user to the service’s authorization page, with the request token as a parameter, where the user can log into the service and authorize the application to access their information.
3. Once the user is finished authorizing, the client application needs to request an access token which will be used to make authorized calls to the service’s API. The service replies to the request with an access token and access secret. The application needs to save both of these securely.
4. The client application can now make API calls by including the user’s access token, and signing the oauth parameters with the access secret.

Laserbeak
I am going to attempt to walk through a “simple” android application that performs the request and authorization steps of OAuth as well as makes an update call to fire eagle with the current location of the phone.

Setup
The first step will be getting your own application key and secret token from the fireeagle service. Fire eagle is currently invite-only but there are plenty of invites floating around.

The second step is to setup a new android project and give it GPS and LOCATION permissions.

The third step will be getting the OAuth java libraries from the OAuth Java repository. Since the libraries use the apache-commons and http libraries that are already included in android you can simply drop the net.oauth, net.oauth.client, and net.oauth.signature into your source directory. Note: The OAuth java libraries aren’t “finished” and not as well documented as the libraries for other languages but I have found them to be fairly straight forward and functional.

The Application
We will create a simple application that consists of an activity with three buttons. Each button’s onClick event will trigger a step in our authorization process. Complete source code for this activity can be found here

Initializing the OAuth provider, consumer, and accessor in the Activity’s OnCreate method:


		serviceProvider = new OAuthServiceProvider(OAUTH_REQUEST,
				OAUTH_AUTHORIZE, OAUTH_ACCESS);

		consumer = new OAuthConsumer("http://www.noredirectfordesktop.com",
				CONSUMER_KEY, CONSUMER_SECRET, serviceProvider);

		accessor = new OAuthAccessor(consumer);

		httpClient = new OAuthHttpClient(new HttpClientPool() {

			public HttpClient getHttpClient(URL server) {
				return new HttpClient();
			}
		});

Here we initialize the classes that will be used to make OAuth requests to the Fire eagle service, we include the three URLs as well as the consumer key and consumer secret. All of the OAuth specific parameters and operations will be performed by these classes.

The request token button:


Button requestButton = (Button) this.findViewById(R.id.req_button);
		requestButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				try {
					httpClient.getRequestToken(accessor);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				// manually set the access token to the request token...not sure
				// why
				accessor.accessToken = accessor.requestToken;

				// start browser application so user can authorize your
				// application
				Intent authIntent = new Intent(Intent.VIEW_ACTION);
				authIntent.setData(Uri.parse(FIRE_EAGLE_AUTHORIZE_URL
						+ accessor.requestToken));
				Laserbeak.this.startActivity(authIntent);
			}

		});

Here we use the built in getRequestToken method to make a token request to the service. If all goes well the token is stored in the requestToken field of the accessor, for the authorization step we need to manually set the accessToken field on the accessor to equal the requestToken.
The next step is interesting in that we need to have the user manually authorize our application, android makes it easy to launch the browser to the authorization URL using a VIEW_ACTION intent. This will launch a browser that the user can use and once they are finished they can simply close the browser and return to the application which is still running in the background.

The authorize button:


Button authButton = (Button) this.findViewById(R.id.auth_button);
		authButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

				try {

					OAuthResponseMessage response = (OAuthResponseMessage) httpClient
							.invoke(accessor.newRequestMessage("GET",
									serviceProvider.accessTokenURL, null));

					// manually set these fields on the accessor from the
					// response
					accessor.accessToken = response.getParameter("oauth_token");
					accessor.tokenSecret = response
							.getParameter("oauth_token_secret");

					//at this point you should store the accessToken and tokenSecret
					//somewhere secure
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

		});

Our application is now authorized to make API calls, lets try calling update with the current Lat/Lon of our phone


Button updateButton = (Button) this.findViewById(R.id.update_button);
		updateButton.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {

					// get current location and use it as params to our API call
					LocationManager locMan = (LocationManager) Laserbeak.this
							.getSystemService(Context.LOCATION_SERVICE);
					Location loc = locMan.getCurrentLocation("gps");

					HashMap params = new HashMap();
					params.put("lat", loc.getLatitude());
					params.put("lon", loc.getLongitude());
					try {

						OAuthResponseMessage response2 = (OAuthResponseMessage) httpClient
								.invoke(accessor.newRequestMessage("POST",
										FIRE_EAGLE_UPDATE_URL, params
												.entrySet()));
					} catch (Exception e) {
						e.printStackTrace();
					}

			}
		});

Here we get the LocationManager and get the user’s current latitude and longitude and put them in a parameter map to be used in the request.

Those are the basic steps for using OAuth and fire eagle. There are a number of things I left out like saving and accessing the access token and access secret from a secure place, as well as saving the state of the accessor for when your application gets interrupted by an incoming call. You could also create a service that updates your location periodically in the background instead of explicitly updating it in an activity.

Unfortunately due to security issues, desktop and mobile applications are only allowed to access the user and update API calls. The more interesting calls that allow you to query all the users of your application and create a social location network are restricted to web applications.

Now that you know how to authorize an application in OAuth you can use the above steps to interact with any other OAuth capable API, like pownce.

Posted on March 13th, 2008 | Filed under android, identity, java, mobile | 9 Comments »

I have been experimenting with implementing a RESTful API in Grails. Like most APIs some of the methods require user authentication before they are allowed to be performed. There are a number of interesting HTTP based authentication/authorization schemes out there, but the most straight forward is Basic Authentication. Basic Authentication takes a Base64 encoded username:password pair and places it into the “Authorization” http header. The server then decodes the pair and uses them with it’s authentication system. It is not the most secure way to do authentication as your user name and password are basically in plain text, but the risk can be mitigated by using https.

There are a number of java packages and grails plugins that provide Basic Authentication functionality amongst other things. I thought I would walk through doing it manually within Grails, since it is fairly straightforward and provides an example of how grails filters can be used.

The main part of the approach is creating a Filter that will intercept the calls to our api and authenticate the user. In the conf directory of your grails project create a groovy class called SecurityFilters.groovy and insert the following:


 class SecurityFilters {
	def filters = {
			basicAuth(controller:'api', action:'*') {
		           before = {
		            	 def authString = request.getHeader('Authorization') 

		            	 if(!authString){
		            		 redirect('500')
		            	 }

		            	 def encodedPair = authString - 'Basic '
		            	 def decodedPair =  new String(new sun.misc.BASE64Decoder().decodeBuffer(encodedPair));
		            	 def credentials = decodedPair.split(':')
		            	 def user = User.findByNameAndPassword(credentials[0],credentials[1])

		            	 if(user){
		            		 session.user = user
		            	 }
		            	 else{

		            		 redirect('500') 

		            	 }
		           }
		     }
}

3: Define a filter called basicAuth which will filter on all controllers and all actions. You can change this to be the specific controller for your API as well as specific the actions you want to authenticate.
4: This specifies that we want a before filter, that will occur before the action is triggered.
5: Extract the value of the “Authorization” header, the value for this is “Basic username:password” where the “username:password” part is Base64 encoded.
7-9: If the request doesn’t have the authorization header we want to redirect the request to an error page, grails already has an URL mapping for “500″ that redirects to an error.gsp, this is fine for now, but you probably want to add a 401 Unauthorized error.

You can do the next few lines a number of ways, I have broken it down into steps to make it easier to follow:

11: Use groovy string-fu to get rid of the “Basic ” part of our authString by subtracting from it.
12: Base64 decode the encoded pair. We could have used grails built in codecs
13: Use a little bit more groovy fu using split() to create an array that contains username and password.
14: Query the User model to match the username and password we just extracted. You should have an authentication scheme that doesn’t involve storing your user’s passwords in plaintext.
16-21: If the user exists we store it in the session and the filter passes to the action, if not redirect with an error.

Posted on March 7th, 2008 | Filed under grails, identity | 2 Comments »

Yesterday, the android team released WikiNotes , a personal wiki(like voodoopad), to help developers new to the platform get the hang of the flow of a typical android application. It provides a nice example of using intents to trigger activities directly, and associating activities with intents for the viewing of URI referenced content from a content provider. It also shows how to implement a content provider that allows the resolution of a URI on a field that isn’t the data’s ID column as well as perform searches via URI.

WikiNotes already provides support for automatically creating links for things like websites, phone numbers, and CamelCase formatted WikiNotes. Since android uses URIs to identify content on the phone, you can create links to any kind of content inside of WikiNotes.

I will provide a quick example of using the Linkify class to create a clickable link in a WikiNote that points to a contact in your address book.(hopefully, I am not stepping on anyone’s toes)

Before we start, since we will be accessing contacts on our phone we need to add the permission android.permission.READ_CONTACTS to our AndroidManifest.xml

Contacts are identified by the URI: content://contacts/people/#. I don’t think anyone would want to have to type out that whole thing on their handset keyboard so I will use the short hand “C:#” to identify a clickable contact in our WikiNote. This doesn’t make it any easier to identify who the contact actually is, but the contact provider currently only allows you to reference them by id number, plus its just easier to use a number for now.

Linkify uses a pattern matcher to identify which part of the string of a TextView to make into a clickable link so our first step is to define a wiki contact regex Pattern. If you open up WikiNotes you will see the declaration and definition for WIKI_WORD_MATCHER. Just under that we will add code for our wiki contact pattern.


private static final Pattern WIKI_WORD_MATCHER;
private static final Pattern WIKI_CONTACT_MATCHER;
static {

// Compile the regular expression pattern that will be used to
// match WikiWords in the body of the note
WIKI_WORD_MATCHER = Pattern.compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b");
//match shorthand C:# for a wiki contact
WIKI_CONTACT_MATCHER =Pattern.compile("\\b[C]+[:]+[1-90-9]+\\b");

The next step is to Linkify the TextView so that when it is clicked it resolves to the full contact URI. Inside of the ShowWikiNotes() we want to add the following below the second Linkify.addLinks()


//add custom linkify match for contacts
Linkify.addLinks(noteView, WIKI_CONTACT_MATCHER,

android.provider.Contacts.People.CONTENT_URI.toString()+"/", null, new TransformFilter(){

public String transformUrl(Matcher matcher, String url) {

String ret = url.substring(2); //parse out the number

return ret;
}

});

This uses the method:

addLinks(TextView text, Pattern p, String scheme, MatchFilter matchFilter, TransformFilter transformFilter)

Where the first two parameter are obvious. Scheme is the uri to prepend to the matched text. MatchFilter which lets you further filter the matched text, and TransformFilter which takes the matched text and lets you change it before it is added to the scheme. In this case the string that is passed to the filter is “C:#” and we want to parse out the number part of the string.

Once you have done this you should be able to type C:1 into your WikiNote, confirm it and it will display a clickable link that will take you to the Contact viewing activity.

Woops… Well this is an interesting error in that it shows a little of how intent filters work. When the link is clicked in the TextView an intent with the View action and Browesable category is launched with it’s data set to the contact URI. The issue is that the ContactViewer activity does not have the the android.intent.category.BROWSABLE intent filter so when the intent is triggered the system can’t find an activity that matches it. Now if it did have that filter it would have displayed the following (hopefully):

As the number of content providers grows we can link to many different kinds of content in the wiki and have android automate the viewing of the content by calling the appropriate view activities. You can have links to music, videos, and images, but interestingly with a little modification you could launch all kinds of applications and intent actions from wiki links. You now have a wiki user interface where your users can easily design their own wiki-based navigation for their phone and it’s content.

Posted on March 5th, 2008 | Filed under android, mobile | No Comments »