14

I'm building an API, protected by Doorkeeper.

If I manually create the user (with password) in the backend, and then post the following to oauth/token, Doorkeeper successfully generates an access token for the user and returns it:

data = {
    username: $("#email_sign_in").val(),
    password: $("#password").val(),
    grant_type: 'password',
    client_id: '880c16e50aee5893446541a8a0b3788....',
    client_secret: 'a5108e1a1aeb87d0bb49d33d8c50d....',
    provider: 'identity'
}

However, I'm trying to get my head around how I could do a sign up flow.

I've happily got users/create working, in so far as it creates a user and password, but I'm not sure how to then generate the Doorkeeper::AccessToken in the next step, and return it to the client. Ideally, after creating the user in the user#create action I'd then redirect to POST to oauth/token, with the user's name and password, but I know that you can't redirect to a POST.

I've had a dig around the Doorkeeper source, but am getting a bit lost in all this clever middleware. Any advice on this is greatly appreciated!

idrysdale
  • 1,551
  • 2
  • 12
  • 23

4 Answers4

28

It was the simplest of things! I was overcomplicating it by trying to POST, when in actual fact I could simply generate the DoorKeeper::AccessToken in user#create, and then return this.

Here's the code to generate the token:

access_token = Doorkeeper::AccessToken.create!(:application_id => application_id, :resource_owner_id => user_id)
idrysdale
  • 1,551
  • 2
  • 12
  • 23
6

I dig a bit in the doorkeeper source code, like the way that creating token using standard api way, you'd better using the following method if you are manually doing this.

find_or_create_for(application, resource_owner_id, scopes, expires_in, use_refresh_token)

for your case

access_token = Doorkeeper::AccessToken.find_or_create_for(application: application, resource_owner_id: user_id)

link to source code of doorkeeper find_or_create_for in doorkeeper

catsky
  • 1,193
  • 10
  • 7
3

In rails we can create access token using DoorKeeper using:

Doorkeeper::AccessToken.create!(
  application_id: nil,
  resource_owner_id: user.id,
  expires_in: 2.hours,
  scopes: 'public'
)
Abhay Nikam
  • 182
  • 1
  • 1
  • 6
0

Ideally, the best answer is not the one you posted, I think itś better to create a controller that inherits from Doorkeeper::TokensController:

# app/controllers/custom_tokens_controller.rb
class CustomTokensController < Doorkeeper::TokensController
  # Override create action
  def create
    (... your custom code ...)
    super
  end
end

Then in routes.rb define a new route like post 'custom_tokens', to: 'custom_tokens#create' or whatever naming you prefer, but the action should be create.

More details about this solution here: https://github.com/doorkeeper-gem/doorkeeper/wiki/Using-Resource-Owner-Password-Credentials-flow

Pere Joan Martorell
  • 2,608
  • 30
  • 29