Python 请求开机自检 - 错误 400



我有这个代码:

import requests
import json 
data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"}
url = 'http://MYURL/connect/token'
response = requests.post(url, json=data, verify=False)
print(response)
print response.reason
print(response.json())

我正在尝试在测试环境中测试与新身份验证服务的连接(这就是验证为 FALSE 的原因(这应该为我提供访问令牌和令牌类型,并且使用它们我可以发布到 API。

但我总是得到:

<Response [400]>  Bad Request   {u'error': u'invalid_request'}

我不确定问题出在哪里? 为什么这是一个糟糕的要求?

看起来您正在尝试使用 client_credientials 授予获取 OAuth 2.0 访问令牌。这在RFC6749中进行了描述

我在这里看到 2 个问题:

  • 您必须将字段发布为application/x-www-form-urlencoded而不是json。为此,请使用data参数request.post()而不是json
  • grant_type值必须client_credentials而不是clientcredentials

这给了:

import requests
data = {"client_id" : "a", "client_secret" : "thisissecret", 
"grant_type" : "client_credentials", "scope" : "PublicApi"}
url = 'http://MYURL/connect/token'
response = requests.post(url, data=data, verify=False)
if response.ok:
print(response.json())

也许您需要设置标题的内容类型?

import requests
import json 
data={"client_id" : "a", "client_secret" : "thisissecret", "grant_type" : "clientcredentials", "scope" : "PublicApi"}
headers = {'content-type': 'application/json'}
url = 'http://MYURL/connect/token'
response = requests.post(url, json=data, verify=False, headers=headers)

相关内容

最新更新