ruby-on-railsoauth-2.0ruby-on-rails-5doorkeeper

I have an Rails APP API with Doorkeeper OAuth2 client_credentials. How to get bearer token information within the controller?


I have an Rails APP API with Doorkeeper OAuth2 client_credentials. I want to get the token information within the controller and get the uid of the user who consumed the bearer token and send a logger.info to the logs. Seeking your suggestions / ideas in mind


Solution

  • I'm̀ not sure if I understood your question correctly but I'll try my best here.

    Once you set up your doorkeeper configuration a helper method called doorkeeper_token will be available in your controller. This method returns a Doorkeeper::AccessToken instance and should have the proper resource owner and application for the issued token.

    If you are using the client credentials flow, your issued token will only contain an application_id but no resource_owner_id (as the resource owner is your user).

    To have a resource owner a token has to be issued by the resource owner password credentials flow.

    As for the log, you could have a before_action in your application_controller (or whatever base controller you use) that calls a method or simply a proc to log the token information:

    before_action :log_token_info
    
    def log_token_info
      # log user name or whatever attribute you wish
      # for the user id you can simply access the doorkeeper.resource_owner_id
      logger.info "Token resource owner: #{doorkeeper.resource_owner.name}"
    end
    

    Same goes for the application related to the token