Search code examples
ruby-on-railsrubydoorkeeper

Is there a way to restrict access to certain applications by specific users?


I have create several applications that communicate with our central auth server via doorkeeper. I want to make some applications accessible/inaccessible for specific users.

Is there a way to restrict access to specific oauth_applications and return a 401?


Solution

  • I believe the easiest way to achieve this would be the following:

    1. In your doorkeeper application, change the Users table to include a permissions relationship. Something like, User -> has many -> permissions

    And those permissions could contain just the name of the application you want to give them access to, (Or the ID of the application, you choose)

    1. Then, in your config/initializer/doorkeeper.rb - inside Doorkeeper::JWT.configure - you add which applications that particular user can access inside the token payload, something like:
    token_payload do |opts|
      ...
      token[:permissions] = user.permissions.pluck(:application_name)
    end
    

    If you are using Doorkeeper without JWT, you can still pass extra information to the token by prepending a custom response to the ResponseToken object like so:

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

    and CustomTokenResponse just need to implement the methods body, like so:

    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
    

    extra information can be found in Doorkeepers' wiki: https://github.com/doorkeeper-gem/doorkeeper/wiki/Customizing-Token-Response and in the Doorkeeper JWT gem: https://github.com/doorkeeper-gem/doorkeeper-jwt#usage