Django OAuth2:通过在Basic标头中传递客户端密码来检索访问令牌

时间:2019-05-29 09:59:13

标签: python django basic-authentication django-oauth

我想使用授权码从我的django服务器检索访问令牌。当我在请求的参数中提供client_id和client_secret时,它可以工作,但是当我使用基本身份验证传递它们时,服务器将响应错误。

我有一个使用django-oauth-toolkit来实现OAuth2身份验证的django服务器。授权代码流程工作顺利,但我想使用基本身份验证来实现它以对客户端进行身份验证。 客户端应用程序已在django管理面板中添加。 服务器和客户端都是我的,但是为了与第三方API将来兼容,我需要在获取访问令牌时为客户端应用程序实现基本身份验证。

在客户端,发送带有参数的客户端信息的请求会获得访问令牌,但是在HTTPBasicAuth中传递信息会给我一个错误。

import base64
import json
from urllib.parse import urlencode

import requests

MY_APP_CLIENT_ID = 'my_client_id'
MY_APP_CLIENT_SECRET = 'my_client_secret'

print('input authorization code:')
oauth_code = input()

headers = {
    'Content-Type': "application/x-www-form-urlencoded",
}

encoded_payload = urlencode({
    'grant_type': 'authorization_code',
    'code': oauth_code,
    'redirect_uri': 'http://localhost/my_app/oauth2/redirect_uri',
    'client_id': MY_APP_CLIENT_ID,
    'client_secret': MY_APP_CLIENT_SECRET
})

response = requests.post('http://localhost:8000/o/token/', data=encoded_payload, headers=headers)

print(response.status_code) # 200
print(response.json()) # {'access_token': 'JEDsAwRh', 'expires_in': 36000, 'token_type': 'Bearer', 'scope': 'my_scope', 'refresh_token': '4TD9gmjb'}

encoded_payload = urlencode({
    'grant_type': 'authorization_code',
    'code': oauth_code,
    'redirect_uri': 'http://localhost/my_app/oauth2/redirect_uri',
})

response = requests.post('http://localhost:8000/o/token/', data=encoded_payload, headers=headers, auth=(MY_APP_CLIENT_ID, MY_APP_CLIENT_SECRET))

print(response.status_code) # 401
print(response.json()) # {'error': 'invalid_client'}

第一种情况使我得到200的状态,并得到{'access_token': 'JEDsAwRh', 'expires_in': 36000, 'token_type': 'Bearer', 'scope': 'my_scope', 'refresh_token': '4TD9gmjb'}作为预期的答复。 第二种情况给我一个401状态和{'error': 'invalid_client'}

我的客户代码是否错误? 根据{{​​3}},OAuth2服务器应使用基本身份验证实现客户端身份验证,但是Django是否实现了它?在服务器端是否需要执行特殊的配置?

0 个答案:

没有答案
相关问题