5

我正在使用门卫宝石

我的 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)
4

4 回答 4

2

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

def doorkeeper_unauthorized_render_options
  {json: '{"status": "failure", "message":"401 Unauthorized"}'}
end
于 2014-12-19T11:26:00.887 回答
1

我不能 100% 确定我是否正确理解了您的问题。您的代码看起来不错,但请求似乎是错误的。

使用 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 分钟内有效。请注意,在自定义 Doorkeeper 路由的情况下,url (/oauth/token) 可能不同。

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

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

您当前收到的 401 Unauthorized 响应意味着身份验证信息(在您的情况下是有效的访问令牌)是错误的或根本丢失。

希望有帮助。

于 2015-02-19T18:16:44.647 回答
0

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

respond_to :html, :json
于 2014-03-13T18:10:44.353 回答
0

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

我们降级了我们的门卫版本,它解决了这个问题。2019 年 3 月

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

于 2019-03-20T17:40:57.613 回答