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

idrysdale picture idrysdale · Nov 20, 2013 · Viewed 10k times · Source

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!

Answer

idrysdale picture idrysdale · Nov 20, 2013

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)