mso-4g
Last Updated: February 25, 2016
·
13.47K
· caherrerapa
2b5034357be2b9fe6285ec359e265c0c

Create an OAuth2 API with doorkeeper and devise in Rails

A good resource to understand the different grants available in OAuth2 please check this

Add doorkeeper and devise to your Gemfile on the API rails app. Also, don't forget to run the generators for them, migrations and to create an application to obtain the app_id and secret from doorkeper ( /oauth/applications ).

Uncomment the "resource_owner_from_credentials" block from the doorkeeper.rb (API side)

resource_owner_from_credentials do |routes|
   u = User.find_for_database_authentication(:email => params[:username])
   u if u && u.valid_password?(params[:password])
end

To expose your controllers functionality as an API i would recommend using rocketpants or grape (if you want something more lightweight).

To call from the client side would be the following using ruby oauth2 gem

require 'oauth2'
callback = "http://localhost:3001/auth/example/callback"
app_id = "PROVIDED_BY_DOORKEEPER"
secret = "PROVIDED_BY_DOORKEEPER"
client = OAuth2::Client.new(app_id, secret, site: "http://localhost:3000/")
auth_url = client.auth_code.authorize_url(:redirect_uri => callback)
token = client.password.get_token('username@example.com', 'password')
Say Thanks
Respond