【问题标题】:Explicitly allow Doorkeeper scope in controller在控制器中明确允许 Doorkeeper 范围
【发布时间】:2018-01-03 21:14:20
【问题描述】:

在我当前的应用程序中,我有两个门卫范围,useradmin。在 doorkeeper documentation 中用于在 API 中设置范围时显示

class Api::V1::ProductsController < Api::V1::ApiController
  before_action -> { doorkeeper_authorize! :public }, only: :index
  before_action only: [:create, :update, :destroy] do
    doorkeeper_authorize! :admin, :write
  end

  ...
end

我不想在每个控制器中都调用门卫,所以在我的 ApplicationController 中我有

module API
  module V1
    class ApplicationController < ActionController::API
      before_action { doorkeeper_authorize! :user, :project }
      ...

    end
  end
end

但我不想让:project 访问每个控制器。有没有办法让我在我们的应用程序控制器before_action { doorkeeper_authorize! :user } 中允许user 并在每个控制器的基础上允许project?即:

module API
  module V1
    class SomeController < ApplicationController
      before_action only: [:index, :show] { doorkeeper_authorize! :project }

      ...
    end
  end
end

【问题讨论】:

    标签: ruby-on-rails doorkeeper


    【解决方案1】:

    使用带有controller_name 的条件句 - smith 如下:

    before_action { doorkeeper_authorize! :project }, if: -> { controller_name == 'some' }

    检查是否应该将参数传递给 lambda,例如:

    if: -&gt;(instance) { instance.controller_name == 'some' }

    【讨论】:

      【解决方案2】:

      我可以通过在API::V1::ApplicationController 中执行以下操作来解决此问题

      module API
        module V1
          class ApplicationController < ActionController::API
            WHITELISTED_PROJECT_CONTROLLERS = %w( projects pre_task_plans
                                                  job_hazard_analyses ).freeze
      
            before_action :authorize!
      
            def authorize!
              if project_scope?
                if !WHITELISTED_PROJECT_CONTROLLERS.include?(controller_name)
                  return user_not_authorized
                end
              end
              doorkeeper_authorize! :user, :project
            end
      
            def project_scope?
              doorkeeper_token&.scopes&.any? { |s| s == 'project' }
            end
      
           ...
      
          end
        end
      end
      

      【讨论】:

        【解决方案3】:

        也许创建自己的过滤器可能是一种选择

        before_action :doorkeeper_user_authorize!,  only: [:create, :update, :destroy]
        protected 
        
        def doorkeeper_user_authorize!
          doorkeeper_authorize!( :user )
        end 
        
        def doorkeeper_project_authorize!
          doorkeeper_authorize!( :user, :project )
        end 
        

        然后在应该允许项目的控制器中

        skip_before_action :doorkeeper_user_authorize!
        before_action :doorkeeper_project_authorize!
        

        【讨论】:

          猜你喜欢
          • 2021-08-30
          • 2016-10-08
          • 1970-01-01
          • 1970-01-01
          • 2015-10-12
          • 1970-01-01
          • 2022-11-03
          • 2020-02-16
          • 2016-10-05
          相关资源
          最近更新 更多