【问题标题】:Rails: Doorkeeper custom response from contextRails:来自上下文的门卫自定义响应
【发布时间】:2020-06-30 00:18:03
【问题描述】:

我们正在使用 Doorkeeper gem 通过 API 对我们的用户进行身份验证。自从我们几年前实施以来,一切都运行良好,我们正在使用password 授权流程,如示例中所示:

resource_owner_from_credentials do |_routes|
  user = User.active.find_for_database_authentication(email: params[:username])

  if user&.valid_password?(params[:password])
    sign_in(user, force: true)
    user
  end
end

Doorkeeper 与 Devise 结合使用,可启用reconfirmable 策略。正如您在上面的代码中看到的,我们只允许active 用户(也就是拥有确认电子邮件的用户)连接:

User.active.find_.....

问题

我们的规范发生了变化,现在我们希望在登录时返回一个不同的错误(针对/oauth/token),具体取决于用户是否已确认其电子邮件。 现在,如果登录失败,Doorkeeper 将返回以下 JSON:

{
  "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."
}

理想情况下,当且仅当当前尝试登录的电子邮件是unconfirmed时,我们希望能够返回自定义描述

我们已经检查了 Doorkeeper 上的文档,但似乎没有一种简单的方法(如果有的话)可以做到这一点。 resource_owner_from_credentials 方法位于配置中的事实增加了太多的魔力和不够的灵活性。

有什么想法吗?

【问题讨论】:

    标签: devise ruby-on-rails-5 doorkeeper


    【解决方案1】:

    好吧,在深入挖掘之后,我们找到了一种通过覆盖Doorkeeper::TokensController 来解决此问题的简单方法。

    # frozen_string_literal: true
    
    class TokensController < Doorkeeper::TokensController
      before_action :check_if_account_is_pending, only: :create
    
      private
    
      def check_if_account_is_pending
        user = User.find_by(email: params['username'])
        render json: unconfirmed_account_error if user && !user.confirmed?
      end
    
      def unconfirmed_account_error
        { error: 'invalid', error_description: 'You must validate your email address before login' }
      end
    end
    

    我们还需要确保路由指向自定义控制器:

    use_doorkeeper do
      controllers tokens: 'tokens'
    end
    

    希望以后能帮到别人

    【讨论】:

      猜你喜欢
      • 2018-06-30
      • 2019-08-03
      • 1970-01-01
      • 1970-01-01
      • 2020-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多