python-3.xpython-requestsflask-jwt-extended

How to use jwt authorization with python's library requests?


I'm developing a Flask RESTFULL API with flask_jwt_extended library as extension for authorization.

Now, I have two usuals resources for register an user and for login, that works perfectly. With login resource an user can give their email and password and get back a token. From Postman this token works as expected using Bearer Token mode.

However, I need to make some requests directly from Python3 terminal. Until now, I was using a simple name-password authentication in my requests, so an example of a request would be:

import requests as rs

rs.get('http://localhost:5000/api/samples', auth = ('user', 'pass'))

Now, using jwt tokens, I'm trying the following:

import requests as rs

# xxxxxx is a really long string got previously with login resource

rs.get('http://localhost:5000/api/samples', auth = ("xxxxxx"))

but this approach give to me:

TypeError: 'str' object is not callable

In other posts I've checked that this type of authorization is made through headers, so I've also tried:

import requests as rs

# xxxxxx is a really long string got previously with login resource

rs.get('http://localhost:5000/api/samples', headers = {'Authorization': 'access_token xxxxxx'})

and the error here is an instantly 401 http response.

Hope someone could help me!

Thanks you in advance!


Solution

  • If someone comes here looking for an answer: you just need to add a header just like the following

    headers = {'Authorization': 'Bearer {token}'}
    

    Source: https://reqbin.com/req/python/5k564bhv/get-request-bearer-token-authorization-header-example