Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a new user with credentials, then obtaining a token for that user with Doorkeeper in an API

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!

like image 689
idrysdale Avatar asked Nov 20 '13 00:11

idrysdale


2 Answers

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)
like image 197
idrysdale Avatar answered Nov 15 '22 21:11

idrysdale


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

like image 5
catsky Avatar answered Nov 15 '22 22:11

catsky