无法覆盖门卫中的自定义令牌错误响应

Jig*_*ggs 2 ruby-on-rails oauth doorkeeper ruby-on-rails-5

我想重写门卫令牌错误响应主体方法。目前,当我在 url 处传递错误的用户名和密码http://localhost:3000/oauth/token时,它会给出以下错误消息。

对于未经授权的默认门卫响应:

{
    "error": "invalid_grant",
    "error_description": "The provided authorization grant is invalid, expired, revoked, does not match the redirection URI used in the authorization request, or was issued to another client."
}
Run Code Online (Sandbox Code Playgroud)

但我想要为我的 API 提供不同的错误消息结构。如下所示。

我的预期回应是:

{
    "status_code": 401,
    "message": "Invalid username or password."
    "result": []
}
Run Code Online (Sandbox Code Playgroud)

我遵循这里的官方文档并尝试在下面完全满足我的期望。

尝试自定义响应:

在下面lib/doorkeeper/oauth/error_response.rb

module Doorkeeper
  module OAuth
    class ErrorResponse
      def body
        {
          "status_code": 401,
          "message": "Invalid username or password."
          "result": []
        }
      end
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

门卫配置:

这是doorkeeper.rbconfig -> 初始化程序文件夹下的文件

Doorkeeper.configure do
  ...
  # This block will be called to check whether the resource owner is authenticated or not.
  resource_owner_authenticator do
    fail "Please configure doorkeeper resource_owner_authenticator block located in #{__FILE__}"
  end

  # In this flow, a token is requested in exchange for the resource owner credentials (username and password)
  resource_owner_from_credentials do |routes|
    user = User.find_for_database_authentication(:username => params[:username])
    if user && user.valid_for_authentication? { user.valid_password?(params[:password]) }
      user
    end
  end
  ...
end
Run Code Online (Sandbox Code Playgroud)

但似乎不起作用。它给出的结果与之前给出的结果相同。它不会进入lib/doorkeeper/oauth/error_response.rb文件。

我自动加载 lib 文件夹中的文件,applicatoin.rb例如

module DaihatsuMimamoriApi
  class Application < Rails::Application      
    # config.autoload_paths += %W(\#{config.root}/lib)
    # config.autoload_paths += Dir[Rails.root.join('app', 'lib', '{**/**}')]
    config.autoload_paths += Dir["#{config.root}/lib/**/"]
    # config.autoload_paths << Rails.root.join('lib')
  end
end
Run Code Online (Sandbox Code Playgroud)

尝试了很多自动加载语法但没有成功。

Jig*_*ggs 5

经过多次尝试我得到了解决方案。我不知道这是好方法还是不好,但它现在正在工作。

我所做的是

1)在lib文件夹下创建custom_token_error_response.rb文件。然后重写bodydoorkeeper oauth错误模块的方法。

lib/custom_token_error_response.rb

module CustomTokenErrorResponse
  def body
    {
      status_code: 401,
      message: I18n.t('devise.failure.invalid', authentication_keys: User.authentication_keys.join('/')),
      result: []
    }
    # or merge with existing values by
    # super.merge({key: value})
  end
end
Run Code Online (Sandbox Code Playgroud)

2)将此模块添加到初始化程序文件的门卫ErrorResponse模块中doorkeepr.rb。(检查下面代码中的最后一行)

config/initializer/doorkeeper.rb

Doorkeeper.configure do
  ...

  # In this flow, a token is requested in exchange for the resource owner credentials (username and password)
  resource_owner_from_credentials do |routes|
    user = User.find_for_database_authentication(:username => params[:username])
    if user && user.valid_for_authentication? { user.valid_password?(params[:password]) }
      user
    end
  end
  ...
  #
  # grant_flows %w(authorization_code client_credentials)
  grant_flows %w(password)

  # Under some circumstances you might want to have applications auto-approved,
  # so that the user skips the authorization step.
  # For example if dealing with a trusted application.
  # skip_authorization do |resource_owner, client|
  #   client.superapp? or resource_owner.admin?
  # end
  skip_authorization do
    true
  end
end

Doorkeeper::OAuth::ErrorResponse.send :prepend, CustomTokenErrorResponse
Run Code Online (Sandbox Code Playgroud)

3)现在重新启动你的rails服务器,你就完成了。

您也可以参考我写的集成Rails API + Devise + Doorkeeper 的这篇博客。 https://scotch.io/@jiggs/rails-api-doorkeeper-devise

或者

https://medium.com/@khokhanijignesh29/rails-api-doorkeeper-devise-4212115c9f0d