Testing an OAuth Provider in your Rails App

Recently I received a request from another B2B SaaS vendor to integrate with Catch the Best, so their users could pull their data from Catch the Best into this app. This is a classic use-case for OAuth, so I dove in to learning how to make my Rails app an OAuth provider. Well, thanks to the OAuth gem and the OAuth Rails plugin, it only took an hour or two to do.

However, since it took a little longer than it should have to do some testing of the app from the console, I thought I'd post this code in case it proves helpful to someone else working on this. My goal was to manually verify that the access control (the before filter) was working properly, so I could email the details on the OAuth endpoint to this other vendor and be reasonably sure it would work well for them. Here's the code:

On line 1 I create a new ClientAppliction in my app. This is basically "registering" the other vendor's app as a application that my users choose to receive access to their data. In other words, this is the same thing that developers do when they register a new application with Twitter when they want to get access to a Twitter user's account via OAuth, and then the Twitter user can grant access to that registered application. This is the only line in the code that is related to the provider.

Line 3 creates a new consumer, using the key and secret generated by the provider, and line 4 creates a request token that the other vendor (the consumer app) would use to send their user to my site to request permission (line 6). After the user clicks the "grant access" checkbox and submits the form, a new RequestToken is created for the consumer (used in line 10) and optionally redirects back to the consumer app.

On line 14 I get an access token based on the information received from the ResponseToken (or from the redirect, in the real world), which allows the consumer to act in the place of the user, as if the consumer app were logged in as the user. Finally, line 15 loads a protected action from the app that blocks access with either the oauth_required or the login_or_oauth_required before filter.

Of course you'd want to put something like this into a functional test, but it's nice to be able to see things work in the console, too.

Comments