如何使python请求(oauth2)



我需要得到令牌,使最后的API休息请求。api的规格如下:

  1. basicAuthentication使用:client_idclient_secret(均为url编码,RFC6749)由分号"{{client_id}}:{{client_secret}}"base64 encoded

  2. 输入请求的代码是authorization code(这个代码我已经有了)

  3. 这是oauth2 flow,所以获取代码,然后用代码获取授权代码,使最终api请求。

从api的网站这里是一个示例请求获得最终令牌:

POST /connect/token HTTP/1.1
Host: identityservice.nmbrs.com
Authorization: Basic {{basicAuthentication}} 
Content-Type: application/x-www-form-urlencoded 
grant_type=authorization_code
&code={{code}}
&redirect_uri={{redirect_uri}}

,这应该是响应(来自api站点的一个示例)

{
"access_token": {{access_token}},
"expires_in": 3600,
"token_type": "Bearer",
"refresh_token": {{refresh_token}},
"scope": {{scopes}}
}

现在我想用python发出请求:

url = "https://identityservice.nmbrs.com/connect/token"
headers = {
"grant_type=authorization_code"
'Content-Type': "application/x-www-form-urlencoded",
'client_id':"23232323",     //example
'client_secret':'12344555', //example
'code':'1223455',           //i have this code
'redirect_uri':'http://localhost:8080/callback'

}

response = requests.request("POST", url,  headers=headers)
print(response)
我得到一个403错误,我不认为我的代码是正确的。我应该得到access_token.

我一直在尝试连接到与您相同的服务。下面是我让它工作的方法:

进口
import urllib.parse
import base64
import requests

Credentais

client_id = ""
clientSecret = ""
authorization_code = ""

编码URL编码client_id和clientSecret

client_id = urllib.parse.quote(client_id.encode('utf8'))
clientSecret = urllib.parse.quote(clientSecret.encode('utf8'))

用分号"{client_id}:{client_secret}"和base64编码。

code_bytes = f"{client_id}:{clientSecret}".encode('ascii')
base64_bytes = base64.b64encode(code_bytes)
base64_code = base64_bytes.decode('ascii')

设置请求

你一直得到403错误,因为你没有包含User-Agent头。

url = "https://identityservice.nmbrs.com/connect/token"
headers ={
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36',
'Content-Type': "application/x-www-form-urlencoded",
'Authorization': f"Basic {base64_code}"
}
data = {   
"grant_type" : "authorization_code",
'code': authorization_code , 
'redirect_uri': redirect_uri
}
response = requests.post(url, data=data, headers=headers)
print(response)
print(response.text)

我希望这对你有帮助:)

相关内容

  • 没有找到相关文章

最新更新