使用带有Doorkeeper的客户端凭据在OAuth中发布

时间:2022-07-07 15:22:23

I've implemented a REST API and protected it with doorkeeper. I've written a small client program to access it and it works fine using the resource owner credential flow.

我已经实现了一个REST API并用门卫保护它。我编写了一个小型客户端程序来访问它,它使用资源所有者凭据流工作正常。

Now I'm trying to implement a call using the client credentials flow. So I've followed the example in the link.

现在我正在尝试使用客户端凭据流实现调用。所以我按照链接中的示例进行了操作。

Everything works great when I'm using a GET request, but when I'm using a POST request, I'm getting a 401 Unauthorized. This is a call to a method that doesn't require a resource owner.

当我使用GET请求时,一切都很好,但是当我使用POST请求时,我收到了401 Unauthorized。这是对不需要资源所有者的方法的调用。

The only relevant thing I have in my API controller is:

我在API控制器中唯一相关的事情是:

doorkeeper_for :all

I haven't implemented any scopes or nothing of that kind (am I required to?).

我没有实现任何范围或任何类型的东西(我是否需要?)。

My client code looks like this (exactly as in the example in github):

我的客户端代码看起来像这样(与github中的示例完全相同):

require 'rest-client'
require 'json'

client_id = 'my_client_id...'
client_secret = 'my_client_secret...'

response = RestClient.post 'http://localhost:3000/oauth/token', {
  grant_type: 'client_credentials',
  client_id: client_id,
  client_secret: client_secret
}
token = JSON.parse(response)["access_token"]

# this line works great:
RestClient.get 'http://localhost:3000/api/v1/flights.json', { 'Authorization' => "Bearer #{token}" }
# this line always fails (401 Unauthorized):
RestClient.post 'http://localhost:3000/api/v1/flights.json', { 'Authorization' => "Bearer #{token}" }

Any idea what I may be doing wrong? Is there something special I should do in my application in order to enable the client credentials flow?

知道我可能做错了什么吗?我的应用程序中是否应该执行一些特殊操作以启用客户端凭据流?

1 个解决方案

#1


16  

I figured it out. The problem was that I didn't use RestClient.post properly. The second parameter should be the payload and the third should be the header. It should be something like this:

我想到了。问题是我没有正确使用RestClient.post。第二个参数应该是有效载荷,第三个应该是标题。它应该是这样的:

RestClient.post 'http://localhost:3000/api/v1/flights.json', {}, { 'Authorization' => "Bearer #{token}" }

#1


16  

I figured it out. The problem was that I didn't use RestClient.post properly. The second parameter should be the payload and the third should be the header. It should be something like this:

我想到了。问题是我没有正确使用RestClient.post。第二个参数应该是有效载荷,第三个应该是标题。它应该是这样的:

RestClient.post 'http://localhost:3000/api/v1/flights.json', {}, { 'Authorization' => "Bearer #{token}" }