Skip to content

Customizing Token Response

Nikita Bulai edited this page Nov 13, 2022 · 7 revisions

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. Define it in a separate module, lib/custom_token_response.rb for example:

module CustomTokenResponse
  def body
    additional_data = {
      # use any global storage like RequestStore / Rails Current / etc
      '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"

config.after_initialize do
    ...
    require 'custom_token_response'

end

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

Doorkeeper.configure do
  # ...
end

Rails.application.config.to_prepare do
  Doorkeeper::OAuth::TokenResponse.send :prepend, CustomTokenResponse
end

And that is all you need! You can try to check it from the rails console now:

2.3.1 :001 > Doorkeeper::OAuth::TokenResponse.new(Doorkeeper::AccessToken.last).body
  Doorkeeper::AccessToken Load (1.1ms)  SELECT  "oauth_access_tokens".* FROM "oauth_access_tokens"  ORDER BY "oauth_access_tokens"."id" DESC LIMIT 1

 => {
      "access_token"=>"23b0d7899b9bd8e0ac04b4e28d2cea236765ed6fed4e059143ace6098b07baf7",
      "token_type"=>"bearer",
      "created_at"=>1478174449,
      "username"=>"John Doe"
    }
Clone this wiki locally