python-3.x - Python - 基本授权 (OAuth2.0) 从 API 检索访问 token

标签 python-3.x api oauth-2.0 python-requests authorization

我正在尝试使用以下必需信息从 API 生成访问 token :

授权端点:https://api.paylocity.com/IdentityServer/connect/token

授权 header 该请求预计采用基本身份验证请求的形式,其中“Authorization” header 包含 client-id 和 client-secret。这意味着标准的 base-64 编码的 user:password,前缀为“Basic”作为 Authorization header 的值,其中 user 是客户端 ID,密码是客户端 secret 。

内容类型 header “Content-Type” header 必须为“application/x-www-form-urlencoded”。

其他值 请求必须在请求正文中发布以下表单编码值:

grant_type = client_credentials 范围 = WebLinkAPI

我尝试使用 Python 'requests' 包但没有成功,请参见下文:

import requests

url = "https://api.paylocity.com/IdentityServer/connect/token"

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

body = {
    'grant_type': "client_credentials",
    'scope': 'WebLinkAPI'
}

response = requests.request("POST", url, headers=headers, params=body)

print(response.text)

我收到的不是访问 token ,而是错误消息:

{“错误”:“invalid_client”}

我已经验证我的 Base64 编码的用户名和密码是正确的,它看起来像“G/RaNdOm:MoReRaNdOm==”,当我将它们添加到 postman 时,它可以工作,所以我的凭据是正确的。可能出了什么问题?

最佳答案

我解决了这个问题。有两个问题,授权 header 未使用 ASCII 作为采用 Base64 编码的目标字符集。另一个问题是尝试将附加值添加到参数而不是请求包中的正文中。解决方案是将“params”替换为“data”。解决方案如下:

url = "https://api.paylocity.com/IdentityServer/connect/token"

body = "grant_type=client_credentials&scope=WebLinkAPI"
headers = {
    'Content-Type': "application/x-www-form-urlencoded",
    'Authorization': "Basic ***(base64ASCII)username:password***",
    }

response = requests.request("POST", url, data=body, headers=headers)

print(response.text)

关于python-3.x - Python - 基本授权 (OAuth2.0) 从 API 检索访问 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56877052/

相关文章:

python - 为什么 subprocess.Popen 参数长度限制小于操作系统报告的长度?

python-3.x - 如何使用 _bz2、_sqlite 和 _ssl 从源代码构建 python 3.3.2

c# - 如何获取绘图板笔压力值?

ember.js - 使用 Oauth2 token 恢复没有电子邮件和密码的 session

c# - 使用 Azure AD 客户端凭据授予流程的 Azure Devops Access

python - 在 open() 中处理 logrotate

python - 属性错误: 'str' object has no attribute 'name' PySpark

node.js - SailsJs 响应 (res) 生命周期

api - 用于登录到我的 api 的 Firebase token

angular - 如何在 Azure AD 上注册单租户 SPA?