Sending JWT Get Request containing username/passwo

2019-09-16 19:28发布

问题:

I have access to an API that I'm trying to start leveraging to automate some tasks and I jumped right into it but was stymied by JWT, which I have never used. I'm also coming off a couple years not using python, so I'm a little rusty. Please bear with me.

Here is a direct quote from the API documentation:

The authentication mode for an organization is with a JSON Web Token. Users 
must pass a JSON Web Token (JWT) in the header of each API request made. 

To obtain the JWT, send the user’s API key (UUID) and password in a JSON Web
Token GET Request. The authorization method of “Bearer” and a 
space is then prefixed to the encoded token string returned. The token will 
be tied to the user account that generated the JWT.

I've tried with requests but I'm get 405 errors, I've also installed and imported pyjwt but it's confusing to me. This is essentially what I'm trying to send via python:

POST https://<our endpoint>/v1/token/get HTTP/1.1
Content-Type: application/json
{
"username": "<myUsername>",
"password": "<myPassword>"

I've verified that the target API is working, as there is a small set of functionality that works without JWT and was easily accessed via requests

Advice is welcome, as are any tutorials. I've tried to read several JWT tutorials but I'm having a hard time translating it to python.

Thanks!

回答1:

Question: To obtain the JWT, send the user’s API key (UUID) and password in a JSON Web Token GET Request

Solution using python_jwt.

Assumptions:
Encoding Method = HS256
claims Fieldname 'consumerId'
claims Fieldname 'httpMethod'

Your JWT in the url looks like:

'http://httpbin.org/get?eyJ0eXAiOiAiSldUIiwgImFsZyI6ICJIUzI1NiJ9... (omitted for brevity)  

response.json() contains the requested JWT you have to use afterwards.

Note: Your have to use https://<base url>/v1/token/get

import python_jwt as jwt
# Create claims dictionary for generation of JwToken
claims = {
    'consumerId': 'My App ID',
    'httpMethod': 'GET'
}

import datetime
# create JWToken
jwtoken = jwt.generate_jwt(claims, 'My secret', 'HS256', datetime.timedelta(minutes=5))

response = requests.get('http://httpbin.org/get', jwtoken)
print(response.json())

Tested with Python:3.4.2 - requests:2.11.1



标签: python jwt