Skip to content

Testing your provider with OAuth2 gem

felipeelias edited this page Nov 29, 2011 · 11 revisions

Set up the client

To test your provider, first make sure you have installed the oauth2 gem.

Go to your provider and create a client for you. If you haven't set up a provider yet, you can download this provider example built with Devise.

You can fill in any redirect uri for now since we're not using an web app. For testing purposes, fill in with http://localhost:8000.

To setup the client, go to your terminal and fire up irb and type:

require 'oauth2'

client_id     = '...' # your client's id generated with rake db:setup
client_secret = '...' # your client's secret
redirect_uri  = '...' # your client's redirect uri
site          = "http://localhost:3000" # your provider server, mine is running on localhost

client = OAuth2::Client.new(client_id, client_secret, :site => site)

Now that your client is ready, you can request an authorization code.

Authorization Code

Grab the authorization url with:

client.auth_code.authorize_url(:redirect_uri => redirect_uri)
# => http://localhost:3000/oauth/authorize?response_type=code&client_id=...&redirect_uri=...

Go to this url in your browser. You'll see the authorization endpoint. If you authorize, you'll be redirected to the client's redirect uri (localhost:8000).

You may get an error since this url points to nowhere but don't worry, in the returned url you'll see the code parameter. With this code you will request the access token.

Access token

To request an access token, type:

code = "..." # code you got in the redirect uri
token = client.auth_code.get_token(code, :redirect_uri => redirect_uri)
# => <#OAuth2::AccessToken ...>

You now have access to the provider's API, if you have any. If you downloaded the provider example, you can get all profiles resources:

response = token.get('/api/v1/profiles.json')
JSON.parse(response.body)
# => [ { "username": "something", ... } ]

Congratulations! You just made your first request to the doorkeeper provider!

Clone this wiki locally