Now that the OAuth standard has been finalised and the Rails plugin (as well as libraries for a number of other languages) has stablised, I thought it time to become an early adopter and add it to 88 Miles.
OAuth works like this:
- A developer create a third-party application (a consumer). They login to the the provider website and add their application. The website will then given them a secret key and three URLs: one to get a request token, one to get an access token and one that users can use to authorize an application.
- When another user decides to use the third-party application, they first need to authorize it’s use. So the application will request a Request Token by posting some data to the request token URL.
- Once this returns, the application should redirect, or at least point to the authorization URL. On this page, the user is asked whether they really want to give access to the third party application.
- If the user says yes, the provider will redirect the user back to the consumer website, or at least notify the user that the consumer has authorization (It’s a bit hard to redirect to a desktop application for example).
- Once the consumer is notified that it has been given access, it will then swap it’s Request Token for an Access Token.
- Now the consumer can freely access resources from the provider by using this Access Token.
Obviously, if a given instance of an application has a valid Access Token, it can skip steps 1-5, and just continue using the Access Token.
Although the Rails plugin is aimed at people using acts_as_authenticated, a little bit of hacking and code diving meant it was relatively easy to shoe-horn it into my custom login system. Because I wanted 88 Miles to drop-back to basic authentication if OAuth wasn’t available, I needed to work out what authentication system each request required. This can be done by:
request_proxy = OAuth::RequestProxy.proxy(request) if(request_proxy.signature_method != nil) # It's an OAuth request if oauthenticate # They get access else # Denied! end end
Nice and easy. I did go through and spruce up some of the authentications screens, but if you aren’t that anal, the boilerplate code from the plugin would suffice.