设计 API sign_in不适用于邮递员



我在API模式下使用Rails 6和最新版本的设计。

我为sign_in和sign_up创建了 rspec 测试,它工作正常,他们接受 json 答案并以 json 格式响应

当我尝试使用邮递员测试我的 API 时,它适用于sign_up,但不适用于sign_in。

与邮递员一起,我得到了以下回报

{
"sucess": false,
"message": "fail myapp_failure_app"
}

所以我试图挖掘问题devise gem,我终于发现问题就在这里

def create
self.resource = warden.authenticate!(auth_options)
...
end

warden gem,问题发生在方法_run_callbacks(*args)

def _run_callbacks(*args) #:nodoc:
self.class._run_callbacks(*args)
end

传递给此方法的参数包括:

[:after_set_user, #<User id: 4, nickname: "max", email: "test@test", birth_at: nil, created_at: "2020-01-12 22:44:19", updated_at: "2020-01-13 21:44:57">, Warden::Proxy:70223361236700 @config={:default_scope=>:user, :scope_defaults=>{}, :default_strategies=>{:user=>[:jwt, :rememberable, :database_authenticatable]}, :intercept_401=>false, :failure_app=>MyappFailureApp}, {:scope=>:user, :recall=>"sessions#new", :store=>true, :event=>:authentication}]

如果我将方法更改为此

def _run_callbacks(*args) #:nodoc:
return
self.class._run_callbacks(*args)
end

它运作良好。

我希望通过挖掘宝石并将我的结果与我的规格进行比较来自己找到解决方案,但老实说,我不明白这种方法到底有什么作用以及为什么它与我的规格不同。

Devise定义了warden上的多个钩子,这些钩子通过_run_callbacks方法调用。 看起来您在其中一个回调钩子中失败了。钩子可以在 Devise 源代码中找到。 此外,您的MyappFailureApp并没有真正显示错误,是否可以定义一个更好的错误?像——

class MyappFailureApp < Devise::FailureApp
def respond
http_auth
end
def http_auth
self.status = 401
self.headers["WWW-Authenticate"] = %(Bearer realm=#{Devise.http_authentication_realm.inspect}) if http_auth_header?
self.content_type = 'application/json'
self.response_body = http_auth_body
end
def http_auth_body
{ error: [i18n_message] }.to_json
end
def request_format
:json
end
end

最新更新