使用Python的oAuth2进行RESTAPI身份验证时出现的问题

2024-10-03 21:25:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用一个Rest Api,该Api具有oAuth2身份验证,使用门户管理控制台中生成的apikey来检索访问令牌,然后该令牌将用于所有请求。在文档中,他们提供了一个使用curl检索acceess令牌的示例请求,如下所示:

curl --request POST \
  --url https://exampleurl.com/oauth2/token \
  -u apitoken:abcsdsadssfsagasagasgasgasgasg \
  --data grant_type=client_credentials

使用这个脚本是可行的,我得到一个访问令牌作为响应。 现在我正在使用python,到目前为止还不能得到相同的结果。我一直在编写的代码如下所示:

import requests 
headers={'apitoken': 'abcsdsadssfsagasagasgasgasgasg'}
data={'grant_type': 'client_credentials'}
try:
    r = requests.post('https://exampleurl.com/oauth2/token', headers=headers, data=data)
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

运行此脚本会出现401 HTTP错误“url未经授权”。 感谢您的帮助


Tags: httpscomtokenapiurldatatypecurl
1条回答
网友
1楼 · 发布于 2024-10-03 21:25:30

通过使用curl命令的-u选项,可以设置头'Authorization: Basic your_credentials',其中your_credentials部分是字符串apitoken:abcsdsadssfsagasagasgasgasgasg的base64编码版本。因此,在Python中,您可以将授权标头设置为:

import base64
your_credentials = "{}:{}".format('apitoken', 'abcsdsadssfsagasagasgasgasgasg')
your_credentials_base64 = base64.b64encode(your_credentials.encode())
headers={'Authorization': 'Basic {}'.format(your_credentials_base64)}
data={'grant_type': 'client_credentials'}
try:
    r = requests.post('https://exampleurl.com/oauth2/token', headers=headers, data=data)
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)

或者,您可以使用requests.auth

import requests
from requests.auth import HTTPBasicAuth
data={'grant_type': 'client_credentials'}
try:
    r = requests.post('https://exampleurl.com/oauth2/token', data=data, auth=HTTPBasicAuth('apitoken', 'abcsdsadssfsagasagasgasgasgasg'))
    r.raise_for_status()
except requests.exceptions.HTTPError as err:
    raise SystemExit(err)


相关问题 更多 >