首页 > 解决方案 > 从 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]>

需要帮助 !

标签: pythonrestcurlpython-requestsjwt-auth

解决方案


您正在传递一个字典,您应该在其中传递 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)

推荐阅读