Skip to content

Customizing access permissions for different users

Kirill Usanov edited this page May 19, 2021 · 7 revisions

Issue

Check user permissions to access the required resource.

Solution

You can do this by implementing the authorize_resource_owner_for_client config option with application and resource_owner arguments in your Doorkeeper initializer.

Example

I've done the following for my many-to-many Rails association of users and oauth_applications:

Migration

Create join table.

class CreateUsersOauthApplications < ActiveRecord::Migration[6.1]
  def change
    create_table :users_oauth_applications do |t|
      t.references :user,              null: false
      t.references :oauth_application, null: false
    end
  end
end

You can change join table name or references names as you want.

Model

Add the has_and_belongs_to_many association to your users model. Note that if you have changed join table name or references names, you need to provide this information to your association.

class User < ApplicationRecord
# ...
  has_and_belongs_to_many :oauth_applications, join_table: 'users_oauth_applications',
                          class_name: 'Doorkeeper::Application', association_foreign_key: 'oauth_application_id'
# ...

Doorkeeper initializer

And finally provide the initializer with authorize_resource_owner_for_client option.

Doorkeeper.configure do
  # ...
  authorize_resource_owner_for_client do |application, resource_owner|
    resource_owner.oauth_applications.ids.include? application.id
  end
  # ...
end

Recommend you not to use #include? directly on ActiveRecord classes, because two equal objects may return false on comparison, because your Doorkeeper Application class may change during the work of application.

Clone this wiki locally