门卫给401未经授权

问题描述 投票:5回答:4

我正在使用门卫宝石

我的ApplicationController看起来像这样:

private
def current_resource_owner
    Person.find(doorkeeper_token.resource_owner_id) if doorkeeper_token
end

我的DemosController看起来像这样:

doorkeeper_for :index
respond_to :json 
def index
    respond_with current_resource_owner
end

回应是这样的:

Started GET "/?code=f88d2e95b1b286645d31772c395e0e36708a5i0p970836af640f631bb4f043b5" for 127.0.0.1 at 2014-01-28 11:10:56 +0530
Processing by DemosController#index as HTML
Parameters: {"code"=>"f88d2e95b1b286645d31135c395e0e36708a5b5b970836af640f631bb4f043b5"}
Filter chain halted as #<Proc:0xb608b90@/home/xyz/.rvm/gems/ruby-1.9.3-p484@verticalserver/gems/doorkeeper-1.0.0/lib/doorkeeper/helpers/filter.rb:8> rendered or redirected
Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
ruby-on-rails ruby http-status-code-401 doorkeeper
4个回答
2
投票

这实际上是门卫的一个问题。要对401 Unauthorized错误而不是空白页面进行自定义JSON响应,在ApplicationController中我添加了:

def doorkeeper_unauthorized_render_options
  {json: '{"status": "failure", "message":"401 Unauthorized"}'}
end

1
投票

如果我理解你的问题,我不是百分百肯定的。您的代码看起来很好,但请求似乎是错误的。

使用Doorkeeper,您需要访问令牌而不是Code参数来访问资源(DemosController #index)。首先,您必须从授权码获取访问令牌。因此提出要求

GET "/oauth/token?code=...&grant_type=authorization_code&redirect_uri=...&client_id=...&client_secret=..."

确保redirect_uri与在客户端应用程序中注册的一个匹配,并将正确的client_id和client_secret添加到请求中。还始终使用新的代码参数。默认情况下,它仅在生成后10分钟有效。请注意,在自定义门卫路由的情况下,url(/ oauth / token)可能不同。

如果您正确完成了请求,则响应将包含有效的访问令牌。

然后向“/index.json?access_token = ...”而不是“/?code = ...”发出GET请求。 '.json'告诉Rails你的客户端可以处理JSON。否则,您将获得406响应,这意味着不支持所请求的格式(默认为HTML)。您也可以在HTTP标头中发送Accept =“application / json”,而不是'.json'。

401 Unauthorized响应,您当前正在接收的内容,意味着身份验证信息(在您的情况下是有效的访问令牌)完全错误或丢失。

希望有所帮助。


0
投票

您的respond_to还需要响应html,因为您要求“DemosController #index为HTML”

respond_to :html, :json

0
投票

可能不是你的答案,但它可能是你的答案。

我们降级了我们的门卫版本,它解决了这个问题。 march2019

https://github.com/doorkeeper-gem/doorkeeper/issues/732

© www.soinside.com 2019 - 2024. All rights reserved.