python - 从 python 脚本访问 JWT 安全的 Restful API
问题描述
我可以使用 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 脚本执行相同操作时,身份验证请求失败并显示消息 <Response [400]>
需要帮助 !
解决方案
您正在传递一个字典,您应该在其中传递 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)
推荐阅读
- python - 如何在kivy轮播中显示多个项目?
- javascript - 通过显示在调试器模式下更改的内容,使用 .net api 强制窗口在 reactjs 中创建 Zip 文件以重新加载
- nginx - 除根以外的其他 NGINX 路由
- c++ - 如何测试两个三角形是否在 3D 空间中碰撞?
- java - 不支持 Spring MVC 请求方法“PATCH”
- apache-spark - 我可以在 Spark Dataframe udf 中使用 java.time.LocalDate 吗?
- javascript - React Antd - 发现 2 个带有非唯一警告的元素
- flutter - 如何在 Flutter 中创建不可滚动的网格?
- sql - Postgresql 选择直到达到一定的总量并锁定
- php - 此路由不支持 GET 方法。支持的方法:POST。Laravel 和 Ajax