viveksrivastava
viveksrivastava

Reputation: 75

How can we customise access token response generated by doorkeeper

I want to add custom attribute to access token generated by doorkeeper.

Doorkeeper::AccessToken.create!(:application_id => application_id, :resource_owner_id => resource_owner_id)

It will create and save access token something like (34100470134f8018e0c30220c972f6540d489df687bb16c2b9d3b04e23168282) in oauth_access_token table

My concern is how i customise this auto generated access token by doorkeeper.

Upvotes: 2

Views: 2266

Answers (1)

Mark
Mark

Reputation: 6445

Following https://github.com/doorkeeper-gem/doorkeeper/wiki/Customizing-Token-Response should help you out:

In some cases you may need to extend OAuth2 token response with some additional data. In order to do that for the Doorkeeper gem you need to override body method of the Doorkeeper::OAuth::TokenResponse class:

## lib/custom_token_response.rb
module CustomTokenResponse
  def body
    additional_data = {
      'username' => env[:clearance].current_user.username,
      'userid' => @token.resource_owner_id # you have an access to the @token object
      # any other data
    }

    # call original `#body` method and merge its result with the additional data hash
    super.merge(additional_data)
  end
end

Don't forget to add lib/ directory to the autoload paths if you are using Rails >= 4.

# config/application.rb

config.autoload_paths << "#{Rails.root}/lib"

Then include that module in a Doorkeeper TokenResponse class by adding the following line to the end of the config/initializers/doorkeeper.rb file:

## config/initializers/doorkeeper.rb
Doorkeeper.configure do
  # ...
end

Doorkeeper::OAuth::TokenResponse.send :prepend, CustomTokenResponse

And you should be good to go!

Upvotes: 7

Related Questions