【问题标题】:How to get an user authentication token in a URL-Encoded form and receive a JWT Token using Python?如何以 URL 编码形式获取用户身份验证令牌并使用 Python 接收 JWT 令牌?
【发布时间】:2019-07-22 12:47:23
【问题描述】:

我正在尝试通过以 URL 编码形式发布用户名、密码并收到 JWT 令牌来生成用户身份验证令牌。

我尝试过使用有效负载而不是标头和两者,但没有任何效果。我正在使用 Python 3.7。

import requests

headers = {'username':'username', 'password':'password'}
r = requests.post("https://sso.xxxxxx.com/sso-api/v1/token", headers=headers)
print (r)

我希望输出 Response 200 Token 生成成功,但我收到错误 Response 404

【问题讨论】:

  • 首先,您尝试将用户名和密码作为标题发送。如果您想将其作为 URL 编码发送,那么您应该执行类似here 描述的操作。此外,您还需要事先了解您的 API 如何向您发送令牌,并且取决于您可以在 json 中或通过标头接收令牌。
  • 您能发布您收到的回复(标题、正文等)吗?
  • 我能够按照您提到的建议运行代码。我解码了 JWT 并收到以下标头 - 'access_token':'xxxx..','id_token':'xxxxx...','token_type':'Bearer'。现在,我需要使用令牌通过 requests.get 下载报告,但不知道如何使用令牌。
  • 大多数 API 都希望令牌在标头中传递。一般规则是在Authorization 标头中发送令牌,如下所示:Authorization: Bearer {your token here}

标签: python-3.x python-requests


【解决方案1】:

我能够在 xbound 的提示和帮助下做到这一点。我不得不将它作为数据传递,而不是标题。然后我确认响应正常并提取令牌。

import requests
payload = {'username':'*******@*********.com', 'password':'**********', 'grant_type':'password', 'scope':'openid'}
r = requests.post("https://***.******.com/***/**/token", data = payload)

##Confirm that reponse is OK!
r.status_code
print(r.status_code == requests.codes.ok)

##Decode json reponse - token
data = r.json()

##Select token
my_token = data['id_token']

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-22
    • 2019-01-22
    • 2021-10-12
    • 1970-01-01
    • 2020-07-07
    • 1970-01-01
    • 2019-11-24
    • 1970-01-01
    相关资源
    最近更新 更多