<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>a walking city &#187; identity</title>
	<atom:link href="http://awalkingcity.com/blog/category/identity/feed/" rel="self" type="application/rss+xml" />
	<link>http://awalkingcity.com/blog</link>
	<description></description>
	<lastBuildDate>Tue, 13 Dec 2011 17:23:53 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.2</generator>
		<item>
		<title>Java, OAuth, Signpost</title>
		<link>http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/</link>
		<comments>http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/#comments</comments>
		<pubDate>Sun, 28 Jun 2009 05:47:59 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[identity]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=163</guid>
		<description><![CDATA[By far the most popular post on this blog is the one regarding using OAuth and Java. At that time OAuth, was still fairly new and I was interested in using the Java implementation with some Android applications I had been working on. The Java reference implementation was new, difficult to build, sparsely documented, and [...]]]></description>
			<content:encoded><![CDATA[<p>By far the most popular post on this blog is the one regarding using OAuth and Java.  At that time OAuth, was still fairly new and I was interested in using the Java implementation with some Android applications I had been working on.  The Java reference implementation was new, difficult to build, sparsely documented, and the API was confusing to say the least.  Months passed and very little was done to the library.  I would probably attribute this to the lack of OAuth enabled web services.  Public key signing was added eventually, but when Android upgraded to HttpClient 4.0, it broke compatibility with the original OAuth library.  A ported version was eventually added to the repository by <a href="http://code.google.com/p/jfireeagle/">Sean Sullivan</a> but the library was still fairly difficult to use.  I, like many people, swore that I would eventually get around to eventually writing a Java OAuth library that was straight forward and easy to use.  </p>
<p>Fortunately for us, Matthias Kappler has written an excellent library called <a href="http://code.google.com/p/oauth-signpost/">Signpost</a> that uses the standard Java URL class, and also supports HttpClient requests.  Signpost does not attempt to perform both signing and requesting like the original library and focuses solely on token acquisition and request signing, which really should be the key parts of any implementation.  There are many examples of using <a href="http://code.google.com/p/oauth-signpost/">Signpost</a> with a number of services, including <a href="http://code.google.com/p/oauth-signpost/wiki/TwitterAndSignpost">Twitter</a> and using the new <a href="http://oauth.net/core/1.0a">OAuth 1.0a</a> spec that addresses the <a href="http://blog.oauth.net/2009/04/22/acknowledgement-of-the-oauth-security-issue/">vulnerability</a> found in the OAuth <a href="http://oauth.net/core/1.0a">spec</a> recently.</p>
<p>You can go to the google code site to check out the library and the basics of token request and authorization (including the new &#8220;pin&#8221; authorization), but I will show you some quick code to perform a status update request with Twitter. This code assumes that you have a valid access token and secret.</p>
<p>Update the user&#8217;s status using URL:</p>
<pre name="code" class="java">

       OAuthConsumer consumer = new DefaultOAuthConsumer(
                &quot;yourappkey&quot;,
                &quot;yourappsecret&quot;,
                SignatureMethod.HMAC_SHA1);
        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                &quot;http://twitter.com/oauth/request_token&quot;,
                &quot;http://twitter.com/oauth/access_token&quot;,
                &quot;http://twitter.com/oauth/authorize&quot;);
        consumer.setTokenAndSecret(AUTH_TOKEN,TOKEN_SECRET);//load these from a db or file
        URL url = new URL(&quot;http://twitter.com/statuses/update.xml?status=&quot; + URLEncoder.encode(&quot;test one two three&quot;));
        HttpURLConnection request = (HttpURLConnection) url.openConnection();
        request.setRequestMethod(&quot;POST&quot;);
        consumer.sign(request);
        request.connect();
        if(request.getResponseCode() == 200)
           return true;
       else
           return false;
</pre>
<p>Performing a status update using HttpClient, assumes mClient is an already initialized HttpClient and excludes exception handling code:</p>
<pre name="code" class="java">

       OAuthConsumer consumer = new DefaultOAuthConsumer(
                &quot;yourappkey&quot;,
                &quot;yourappsecret&quot;,
                SignatureMethod.HMAC_SHA1);
        OAuthProvider provider = new DefaultOAuthProvider(consumer,
                &quot;http://twitter.com/oauth/request_token&quot;,
                &quot;http://twitter.com/oauth/access_token&quot;,
                &quot;http://twitter.com/oauth/authorize&quot;);
        consumer.setTokenAndSecret(AUTH_TOKEN,TOKEN_SECRET);//load these from a db or file
            Uri.Builder builder = new Uri.Builder();
            builder.appendPath(&quot;statuses&quot;).appendPath(&quot;update.json&quot;)
                    .appendQueryParameter(&quot;status&quot;, status);
            Uri man = builder.build();
            HttpPost post = new HttpPost(&quot;http://twitter.com&quot;  + man.toString());
            consumer.sign( post);
            HttpResponse resp = mClient.execute(post);
            if (resp.getStatusLine().getStatusCode() == 200) {
                    return true;
                } else {
                    return false;
                }
</pre>
<p>Hopefully you will also find Signpost to be as useful as I did.  I was able to migrate my twitter application from using basic authentication to using OAuth with Signpost in an hour compared to the hours of pain spent trying to use the original implementation.</p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>OpenID and Grails</title>
		<link>http://awalkingcity.com/blog/2008/03/20/openid-and-grails/</link>
		<comments>http://awalkingcity.com/blog/2008/03/20/openid-and-grails/#comments</comments>
		<pubDate>Thu, 20 Mar 2008 23:51:13 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[identity]]></category>
		<category><![CDATA[java]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=18</guid>
		<description><![CDATA[OpenID is an open standard for decentralized authentication. The OpenID site has plenty of detailed documentation about the protocol so I will briefly explain the basics needed to understand how to integrate OpenID authentication into your grails project. OpenID Provider A user registers an OpenID through an OpenID provider. This is the site that provides [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://openid.net/what/">OpenID</a> is an open standard for decentralized authentication.  The <a href="http://openid.net/">OpenID site</a> has plenty of detailed documentation about the protocol so I will briefly explain the basics needed to understand how to integrate OpenID authentication into your grails project.  </p>
<p><strong>OpenID Provider</strong><br />
A user registers an OpenID through an OpenID provider.  This is the site that provides the identifying URL for the user and handles the authentication request from the Relying Party.</p>
<p>There are a number of OpenID providers out there, with new ones cropping up all the time.  I use <a href="http://myopenid.com">myopenid</a> simply because it was one of the first openid providers I had heard of.  Many sites also provide an OpenID when you sign up for their service.  This has lead to OpenID providers that aggregate all of your other OpenIDs.  Since we want to drive adoption and there are probably more providers than consumers at this point, we are going to focus on just being an OpenID relying party.  </p>
<p><strong>Relying Party</strong><br />
The relying party is the web service that uses OpenID to handle it&#8217;s authentication.  It prompts the user for their OpenID URL and redirects the user&#8217;s browser to the Provider&#8217;s authentication page, the provider prompts the user with information about the site making the authentication request, allows the user to accept or reject authentication with the site and then redirects the user back to the relying party with an authentication token that the relying party then verifies.  The user never enters a password with the relying party, the provider can also allow automatic authentication with the relying party if they so choose. </p>
<p><strong>Discovery</strong><br />
You can use any web address as your OpenID simply by including the following html in the head tag of your site.</p>
<pre name="code" class="html">

&lt;link rel=&quot;openid.server&quot; href=&quot;http://youropenidserverendpoint&quot;&gt;
&lt;link rel=&quot;openid.delegate&quot; href=&quot;http://youropenid/url&quot;&gt;
</pre>
<p>This lets you use your blog and any other site you may have as your OpenID.  The relying party will parse this information from whatever URL you pass to it.  </p>
<p><strong>Setup</strong><br />
I am using code and comments taken from the OpenID4Java <a href="http://code.google.com/p/openid4java/wiki/QuickStart">getting started page</a>  and adapting it for quick integration with grails.  If you need anymore detail than I have provided you should check out their <a href="http://code.google.com/p/openid4java/w/list">wiki</a>. The full source code for our example can be found here:  <a href='http://awalkingcity.com/blog/wp-content/uploads/2008/03/usercontroller.groovy'>UserController.groovy</a></p>
<p>1. Sign up for an OpenID, we want one to ease testing obviously.  </p>
<p>2. Download the excellent OpenID java library OpenID4java and put the jar and its dependencies in your lib directory.  Watch out for dependency versioning conflicts since grails uses many of the same dependencies.</p>
<p>3.  For our example we will use a User controller, so go ahead and create a user controller.  I won&#8217;t really go into modelling a User domain class but with OpenID you can skip all of the password management and storage and simply have a field for their OpenID URL instead.</p>
<p><strong>Getting Started</strong></p>
<p>We need to specify a return URL that the provider will redirect to after authentication is finished.  You can store this in a number of places but I will just put it in the UserController.  This URL corresponds to the auth action will will implement in UserController.</p>
<pre name="code" class="java">

String _returnURL = &quot;http://localhost:8080/openidtest/user/auth&quot;;
</pre>
<p>The controller actions share a ConsumerManager that is used to perform various steps of the OpenID authentication, I made it a static variable in the UserController because it seems to not work otherwise, there is probably a better way to do this.</p>
<pre name="code" class="java">

  static ConsumerManager manager = new ConsumerManager();
</pre>
<p><strong>Actions</strong><br />
We will define a few actions on our controller, these will be used to initiate and verify the OpenID authentication process.</p>
<p><strong>login</strong><br />
The first action is login, this action simply presents the user with an OpenID entry field.</p>
<pre name="code" class="java">

def login = {

    		if(session.user){
    			redirect(action: 'index') //redirect to main user page
    		}
    }
</pre>
<p>If the user is already logged in we redirect.  </p>
<p>Here is gsp code for including an OpenID login field for your app, include it in your login.gsp view.  Don&#8217;t forget to save the OpenID icon to your images directory.</p>
<pre name="code" class="html">

&lt;img src=&quot;${createLinkTo(dir:'images',file:'icon_openid.gif')}&quot; alt=&quot;openid_logo&quot; /&gt;
&lt;g:form name=&quot;loginForm&quot; action=&quot;handleLogin&quot;&gt;&lt;g:textField name=&quot;openid&quot; value=&quot;http://yourname.myopenid.com&quot; /&gt;
&lt;g:actionSubmit value=&quot;Login&quot; action=&quot;handleLogin&quot; /&gt;
&lt;/g:form&gt;
</pre>
<p><strong>handleLogin</strong><br />
This action will take the user&#8217;s OpenID URL, create an authentication request and redirect the user to their OpenID Provider.</p>
<pre name="code" class="java">

def handleLogin = {

    try{
		// disable realm verification
    		 RealmVerifier rv = new RealmVerifier();
    		 rv.setEnforceRpId(false);
    		 manager.setRealmVerifier(rv)

    		 // perform discovery on the user-supplied identifier
    		    List discoveries = manager.discover(params['openid']);
    		    DiscoveryInformation discovered = manager.associate(discoveries);

    		    // store the discovery information in the user's session for later use
    		    session.discovered = discovered

    		    // obtain a AuthRequest message to be sent to the OpenID provider
    		    AuthRequest authReq = manager.authenticate(discovered, _returnURL);

    		    response.sendRedirect authReq.getDestinationUrl(true)
    		    }catch(DiscoveryException e){
    		    	//add flash message , failed to find openid at address
    		    	flash.message = &quot;Failed to find valid openid URI at specified address&quot;
    		    	redirect(action:'login')
    		    }
    }
</pre>
<p><strong>auth</strong><br />
The auth action is the action specified by our service that the OpenID provider will redirect the user to after authenticating with the provider.  The provider includes a number of parameters so that the relying party can verify that the user has actually authenticated with the provider.  </p>
<pre name="code" class="java">

 def auth = {

    	    // check if this is an openid message, this is to avoid someone
	    // calling the auth action themselves
    	    if(!params['openid.mode']){
    	    	redirect(action:'err')
    	    return;
    	    }

    	    ParameterList openidResp = new ParameterList(request.getParameterMap());

    	    // retrieve the previously stored discovery information
    	    DiscoveryInformation discovered = (DiscoveryInformation) session.discovered;

    	    // extract the receiving URL from the HTTP request
	    // is there an easier way to get the full path including servername and port?
    	    StringBuffer receivingURL = new StringBuffer('http://' + request.getServerName() + ':' +
  request.getServerPort() +request.forwardURI);
    	    String queryString = request.getQueryString();
    	    if (queryString != null &amp;&amp; queryString.length() != 0)
    	        receivingURL.append('?').append(request.getQueryString());

    	    // verify the response
    	    VerificationResult verification = manager.verify(receivingURL.toString(), openidResp, discovered);

    	    // examine the verification result and extract the verified identifier
    	    Identifier verified = verification.getVerifiedId();

    	    if (verified != null){
    	    	//User.findByUrl(verfied.getIdentifier())
    	    	session.user = verified
    	    	 // success, use the verified identifier to identify the user
    	    	redirect(action: 'index')

    	    }else{
    	        // OpenID authentication failed
    	        redirect(action: 'err')
    	    }

    }
</pre>
<p>request.forwardURI is a grails specific method that actually calls request.request.requestURI, this is needed to verify the previously called URL that made the authentication call to the provider.  </p>
<p><strong>err</strong><br />
The err action is the action we will redirect to if our authentication fails at any point.   You can probably get away with just redirecting the the grails default error page.  </p>
<p><strong>Filter</strong><br />
Our final step is to set up an Authentication filter like the one we made for <a href="http://awalkingcity.com/blog/?p=12">basic authentication</a> .  The only difference is that we have a number of controller actions that we want to allow to pass the filter, like login, handleLogin, auth, and err. </p>
<pre name="code" class="java">

class SecurityFilters {
	class SecurityFilters {
	def filters = {
			loginCheck(controller:'*', action:'*') {
		           before = {
		        		   log.trace(&quot;inside of filter&quot;)
		              if(!session.user &amp;&amp; !actionName.equals('login') &amp;amp;amp;&amp;amp;amp; !actionName.equals('handleLogin') &amp;&amp; !actionName.equals('auth') &amp;&amp; !actionName.equals('err')) {
		                  redirect(controller:'user' , action:'login')
		                  return false
		               }
		           }

		}
	}
}
</pre>
<p>OpenID, Authorization, and APIs<br />
Since OpenID focuses on authentication there is not currently a good way to incorporate OpenID with API calls.  Having to redirect a user to a web page is not something someone programming a mobile or desktop application wants to do in order to make API calls.  There have been rumblings of integrating an API http header authorization mechanism into the OpenID standard, and of course you could always integrate OAuth and OpenID so the user would only have to do web based authorization once for your application.  </p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/03/20/openid-and-grails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Android and Fire Eagle; OAuth and Java</title>
		<link>http://awalkingcity.com/blog/2008/03/13/android-and-fire-eagle-oauth-and-java/</link>
		<comments>http://awalkingcity.com/blog/2008/03/13/android-and-fire-eagle-oauth-and-java/#comments</comments>
		<pubDate>Thu, 13 Mar 2008 07:02:38 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[android]]></category>
		<category><![CDATA[identity]]></category>
		<category><![CDATA[java]]></category>
		<category><![CDATA[mobile]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=13</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p><strong>Update 2</strong> See this <a href="http://awalkingcity.com/blog/2009/06/27/java-oauth-signpost/">post</a> or just skip straight to this excellent <a href="http://code.google.com/p/oauth-signpost/">library</a> for all of your OAuth and Java needs</p>
<p><strong>*Update*</strong> The code in this entry no longer works with the Android SDK because of the upgrade to HttpClient 4.  The <a href="http://oauth.googlecode.com/svn/code/java/core/">OAuth Java library</a> has been updated to work with HttpClient 4 but I have not looked at it recently <strong>*Update*</strong><br />
<a href="http://fireeagle.com">Fire eagle</a> 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 <a href="http://code.google.com/android/toolbox/apis/lbs.html">Android&#8217;s Location-Based-Services API</a>,  I became more interested in how fire eagle uses <a href="http://oauth.net/">OAuth</a> as it&#8217;s authorization scheme and how it can be used on a smart mobile device.  </p>
<p>      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&#8217;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.  </p>
<p>      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.  </p>
<p>Here is a general outline of the OAuth process from a client application&#8217;s perspective:<br />
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.<br />
2.   The client application then directs the user to the service&#8217;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.<br />
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&#8217;s API.  The service replies to the request with an access token and access secret.  The application needs to save both of these securely.<br />
4.  The client application can now make API calls by including the user&#8217;s access token, and signing the oauth parameters with the access secret.</p>
<p><strong>Laserbeak</strong><br />
I am going to attempt to walk through a &#8220;simple&#8221; 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.  </p>
<p><strong>Setup</strong><br />
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.     </p>
<p>The second step is to setup a new android project and give it GPS and LOCATION permissions.  </p>
<p>      The third step will be getting the OAuth java libraries from the <a href="http://oauth.googlecode.com/svn/code/java/core/">OAuth Java repository</a>.  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&#8217;t &#8220;finished&#8221; and not as well documented as the libraries for other languages but I have found them to be fairly straight forward and functional.</p>
<p><strong>The Application</strong><br />
We will create a simple application that consists of an activity with three buttons.  Each button&#8217;s onClick event will trigger a step in our authorization process.  Complete source code for this activity can be found <a href='http://awalkingcity.com/blog/wp-content/uploads/2008/03/laserbeak.java' title='laserbeak'>here</a></p>
<p>Initializing the OAuth provider, consumer, and accessor in the Activity&#8217;s OnCreate method:</p>
<pre name="code" class="java">

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

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

		accessor = new OAuthAccessor(consumer);

		httpClient = new OAuthHttpClient(new HttpClientPool() {

			public HttpClient getHttpClient(URL server) {
				return new HttpClient();
			}
		});
</pre>
<p>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.</p>
<p>The request token button:</p>
<pre name="code" class="java">

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);
			}

		});
</pre>
<p>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.<br />
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.<br />
<a href='http://awalkingcity.com/blog/wp-content/uploads/2008/03/laserbeak.png'><img src="http://awalkingcity.com/blog/wp-content/uploads/2008/03/laserbeak.png" alt="" title="laserbeak" width="320" height="480" class="alignnone size-medium attachment wp-att-14" /></a><a href='http://awalkingcity.com/blog/wp-content/uploads/2008/03/laserbeak3.png'><img src="http://awalkingcity.com/blog/wp-content/uploads/2008/03/laserbeak3.png" alt="" title="laserbeak3" width="320" height="480" class="alignnone size-medium attachment wp-att-16" /></a></p>
<p>The authorize button:</p>
<pre name="code" class="java">

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(&quot;GET&quot;,
									serviceProvider.accessTokenURL, null));

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

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

		});
</pre>
<p>Our application is now authorized to make API calls, lets try calling update with the current Lat/Lon of our phone</p>
<pre name="code" class="java">

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(&quot;gps&quot;);

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

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

			}
		});
</pre>
<p>Here we get the LocationManager and get the user&#8217;s current latitude and longitude and put them in a parameter map to be used in the request.  </p>
<p>      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.    </p>
<p>      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.  </p>
<p>      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 <a href="http://pownce.pbwiki.com/API%20Documentation2-0#Authentication">pownce</a>.</p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/03/13/android-and-fire-eagle-oauth-and-java/feed/</wfw:commentRss>
		<slash:comments>9</slash:comments>
		</item>
		<item>
		<title>Basic Authentication and Grails</title>
		<link>http://awalkingcity.com/blog/2008/03/07/basic-authentication-and-grails/</link>
		<comments>http://awalkingcity.com/blog/2008/03/07/basic-authentication-and-grails/#comments</comments>
		<pubDate>Fri, 07 Mar 2008 02:29:50 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[grails]]></category>
		<category><![CDATA[identity]]></category>

		<guid isPermaLink="false">http://awalkingcity.com/blog/?p=12</guid>
		<description><![CDATA[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 [...]]]></description>
			<content:encoded><![CDATA[<p>I have been experimenting with implementing a RESTful API in <a href="http://grails.org">Grails</a>.  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 &#8220;Authorization&#8221; http header.  The server then decodes the pair and uses them with it&#8217;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.  </p>
<p>There are a number of java packages and <a href="http://grails.org/Plugins">grails plugins</a> 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.</p>
<p>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:</p>
<pre name="code" class="java">

 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') 

		            	 }
		           }
		     }
}
</pre>
<p>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.<br />
4:  This specifies that we want a before filter, that will occur before the action is triggered.<br />
5:  Extract the value of the &#8220;Authorization&#8221; header,  the value for this is &#8220;Basic username:password&#8221; where the &#8220;username:password&#8221; part is Base64 encoded.<br />
7-9:  If the request doesn&#8217;t have the authorization header we want to redirect the request to an error page, grails already has an URL mapping for &#8220;500&#8243; that redirects to an error.gsp, this is fine for now, but you probably want to add a 401 Unauthorized error.</p>
<p>You can do the next few lines a number of ways, I have broken it down into steps to make it easier to follow:</p>
<p>11:  Use groovy string-fu to get rid of the &#8220;Basic  &#8221; part of our authString by subtracting from it.<br />
12:  Base64 decode the encoded pair.  We could have used grails <a href="http://grails.codehaus.org/Dynamic+Encoding+Methods">built in codecs</a><br />
13:  Use a little bit more groovy fu using split() to create an array that contains username and password.<br />
14:  Query the User model to match the username and password we just extracted.  You should have an authentication scheme that doesn&#8217;t involve storing your user&#8217;s passwords in plaintext.<br />
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.</p>
]]></content:encoded>
			<wfw:commentRss>http://awalkingcity.com/blog/2008/03/07/basic-authentication-and-grails/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>

