【问题标题】:Access Doorkeeper from action Rails Controller从动作 Rails 控制器访问 Doorkeeper
【发布时间】:2016-04-11 11:23:01
【问题描述】:

是否有机会从 Rails 动作控制器访问身份验证的 Doorkeeper 方法?我想仅针对我的一项操作(“显示”)跳过身份验证,但如果适用特定条件,我想调用 apiauthenticate 方法来完成它的工作。所以在“显示”动作中,首先我检查一个条件,如果不适用,那么我需要激活 api_authenticate。我正在启动一个应该调用 api_authenticate 并在那里停止的测试。但是由于某种原因,它一直在继续,并且没有停止。

这是我的控制器的代码

skip_before_action :api_authenticate, only: :show

def show
  param! :id, String, required: true

  post = Services::Posts.find(params[:id])

  if  post.public
    @post = post
    @user_id = nil
  else
    api_authenticate 
    ap "it shouldnt get here if user is not logged in"
    user = current_resource_owner
    @post = Services::Posts.show(params[:id], user)
    @user_id = user.identity rescue nil
  end
end

#more actions....

这是 api_controller.rb 我有验证方法的地方

class ApiController < ApplicationController
  protect_from_forgery with: :null_session

  # Check the user is authenticated
  before_action :api_authenticate

  rescue_from ActionController::RoutingError, :with => :route_error
  rescue_from ::AbstractController::ActionNotFound, :with => :action_error
  rescue_from Exception, :with => :base_error if Rails.env.production?

  def api_authenticate
    doorkeeper_authorize!()
  end
end

【问题讨论】:

    标签: ruby-on-rails doorkeeper


    【解决方案1】:

    我已经实现了类似的东西。没有测试下面的代码,但它应该可以工作。

    skip_before_filter :doorkeeper_authorize! , only: :show
    
    def show
      param! :id, String, required: true
    
      post = Services::Posts.find(params[:id])
    
      if  post.public
        @post = post
        @user_id = nil
      else
        doorkeeper_authorize! 
        ap "it shouldnt get here if user is not logged in"
        user = current_resource_owner
        @post = Services::Posts.show(params[:id], user)
        @user_id = user.identity rescue nil
      end
    end
    

    API 控制器,

    class ApiController < ApplicationController
      protect_from_forgery with: :null_session
    
      # Check the user is authenticated
      before_action :doorkeeper_authorize! 
    
      rescue_from ActionController::RoutingError, :with => :route_error
      rescue_from ::AbstractController::ActionNotFound, :with => :action_error
      rescue_from Exception, :with => :base_error if Rails.env.production?
    
      def doorkeeper_unauthorized_render_options(error: nil)
        response_hash = { status: false, description: error.description, expired: false }
        response_hash[:expired] = true if error.description == "The access token expired"
        { json: response_hash }
      end
    
    end
    

    如果问题仍然存在,请添加传递给显示操作的参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-23
      • 2011-12-11
      • 2014-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-11
      • 2016-02-17
      相关资源
      最近更新 更多