Simple behind-the-scenes API authentication with OAuth2

Like many others I’ve been spending a lot of time with OAuth2 lately. The single-sign-on system we’ve built at GDS acts as a very simple oauth provider for our other apps (effectively just joining up the oauth2-provider and devise gems), and we’re probably going to be extending our API adapter code so that we can use it for those apps whose APIs need authentication.

What I’d not explored for a while was the simplest way to implement app-to-app oauth where there’s no UI for user interaction so over the New Year break I pulled something together for another project. It’s all pretty straightforward but not very well documented so I thought I’d better share.

The easiest thing to do if you want to allow an oauth client to work with your app is just to generate the ID, secret and access token for whoever’s responsible for the app and to provide them (securely) for direct use.

In order to do that in the rails app I was focussed on I knocked up a class to help me with that when using the aforementioned oauth2-provider:

and then a few rake tasks for interacting with it:

In the oauth-provider world, any “authorization” can be owned by a resource, which is any other model in your app. In a standard app like our SSO solution that’ll probably be a user, but in the app I’m working on here it’s an organisation that may have many users. You get access to that resource in your controllers with, eg:

And with that I had my API protected using everyone’s favourite standard authentication protocol.

Tags: , , , , ,


  1. You shouldn’t need to generate your own identifier and secret for clients – oauth-provider should do that for you.

    • Very true – should have covered that. The reason I tend to leave in code to do that is from the way we’ve been setting things up with multiple environments. Really the consistency between environments should be achieved by regularly migrating production databases back to staging/preview, but while we’ve not had that in place we’ve been letting oauth-provider generate them for production and then using those to also create the client in the preview environment.

  2. Did you look at CAS for SSO? If you did, what were your reasons for not using it? Cheers