【问题标题】:Accessing JWT secured Restful API from python script从 python 脚本访问 JWT 安全的 Restful API
【发布时间】:2020-10-17 21:15:03
【问题描述】:

我可以使用 curl 命令访问 JWT 保护的 Restful API,如下所示

#Get the access Token in a variable ID

export ID=`curl  -X POST --header 'Content-Type: application/json' --header 'Accept: application/json' -d '{  "password": "admin",  "rememberMe": true,  "username": "admin"  }' 'http://localhost:8080/api/authenticate' | jq -r .id_token`

#Use this token to access endpoint 

curl 'http://localhost:8080/api/downloads' --header 'Content-Type: application/json' --header 'Accept: application/json' --header "Authorization: Bearer $ID" 

我的验证部分和获取不记名令牌的python脚本如下:

import requests

LOGIN_URL = "http://localhost:8080/api/authenticate"
ENDPOINT_URL = 'http://localhost:8080/api/downloads'
PARAMS = {'password': 'admin','rememberMe': True,  'username': 'admin'  }
r1 = requests.post(LOGIN_URL,  data =PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1)

当我尝试通过 python 脚本执行相同操作时,身份验证请求失败并显示消息

需要帮助!

【问题讨论】:

  • 请将您的错误描述扩展到“它不工作。”之外!
  • 试试r1.get("id_token") 而不是r1.get_dict()['id_token']
  • 通常如果我不确定响应结构并且我知道它是某种字典。我会尝试将.__dict__ 粘贴到变量上。 r1.__dict__。附言。不是所有东西都支持,但大多数主流包类都有这个实现。

标签: python rest curl python-requests jwt-auth


【解决方案1】:

您正在传递一个应该传递 JSON 的字典。

尝试使用 json 而不是数据并传递字典:

import requests

LOGIN_URL = "https://httpbin.org/post"
PARAMS = {'password': 'admin','rememberMe': True,  'username': 'admin'  }
r1 = requests.post(LOGIN_URL,  json=PARAMS, headers={"Content-Type": "application/json","Accept": "application/json"})
print(r1.text)

或传递一个字符串并使用数据:

import requests

LOGIN_URL = "https://httpbin.org/post"
PARAMS = '{"password": "admin", "rememberMe": true, "username": "admin"}'
r1 = requests.post(LOGIN_URL, data=PARAMS, headers={"Content-Type": "application/json", "Accept": "application/json"})
print(r1.text)

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 2020-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 2020-04-28
    相关资源
    最近更新 更多