-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Client Credentials flow
The Client Credentials
flow is probably the most simple flow of OAuth 2 flows. The main difference from the others is that this flow is not associated with a resource owner.
One usage of this flow would be retrieving client statistics for example. Since the access token would be connected to the client only, the access token won't have access to private user data for example.
In your Doorkeeper configuration initializer, have a line like this:
# add other flows to this array if you want more to be enabled, e.g., %w{authorization_code implicit password}
grant_flows ['client_credentials']
Remove the null: false
from the Doorkeeper migration for t.text :redirect_uri column
to allow applications to use the client_credentials flow without specifying a redirect URL.
To get an access token from client credentials flow, you have to do a post
to /oauth/token
endpoint:
POST /oauth/token
Authorization: Basic czZCaGRSa3F0MzpnWDFmQmF0M2JW
Content-Type: application/x-www-form-urlencoded;charset=UTF-8
grant_type=client_credentials
The Authorization header includes the encoded credentials for the client. For more information and options on how authenticate clients, check this page in the wiki.
In ruby, it would be something like this:
require 'rest-client'
require 'json'
client_id = '4ea1b...'
client_secret = 'a2982...'
response = RestClient.post 'http://localhost:3000/oauth/token', {
grant_type: 'client_credentials',
client_id: client_id,
client_secret: client_secret
}
Notice that in this case we used client_id/secret on parameters instead of using the encoded header.
After that you'll have the access token in the response:
token = JSON.parse(response)["access_token"]
# => 'a2982...'
And then, you can request access to protected resources that do not require a resource owner:
RestClient.get 'http://localhost:3000/api/v1/profiles.json', { 'Authorization' => "Bearer #{token}" }
# => "[{"email":"tara_kertzmann@yundt.name","id":25,"name":"Jorge Ward","username":"leonor"}, ...]"
That's everything.