根据传入的请求类型将请求路由到 rails 问题

时间:2021-03-09 16:15:58

标签: ruby ruby-on-rails-5

Rails 版本为 6.0.0.3,Ruby 版本为 ruby​​ 2.6.6-p146

我需要根据请求格式将传入请求发送到应用程序控制器到 2 个不同的关注点。

我有一个应用程序控制器

class ApplicationController < ActionController::Base
  include Authentication
  include Authorization

  before_action :authenticate_or_authorize

  private

  def authenticate_or_authorize
    request.format.json? ? :authorize_request : :authenticate_request
  end
end

我有两个问题,即身份验证和授权。如果传入请求是 JSON 类型,我需要调用授权问题。

如果是非json请求,我需要调用authenticate_request。

这是我的顾虑。

module Authentication
  extend ActiveSupport::Concern

  included do
    before_action :authenticate_request, :return_url
  end

  private

  def authenticate_request
    // do something to authenticate
  end
end

这是第二个问题。

module Authorization
  extend ActiveSupport::Concern
  include ::JwtVerifiable

  included do
    before_action :authorize_request
  end

  private

  def authorize_request
    // do something to authorize.
  end
end

当前的行为是请求总是转到身份验证问题。然后是ApplicationController中定义的authenticate_or_authorize。

谁能帮忙纠正这个问题?

提前致谢。

1 个答案:

答案 0 :(得分:0)

关注点在被包含时已经提供了自己的 before_action 调用(这就是 included do (block) end 正在做的事情)。这意味着 :authenticate_request、:return_url 和 :authorize_request 将在每个请求上运行。如果您无法从关注点中消除这些问题,请跳过它们:

skip_before_action :authenticate_request, :authorize_request

在 ApplicationController 中包含关注点之后。您在 ApplicationController 中定义的 before_action 仍会运行。