How to define a header with a JWT token in a request made by the Requests library?

5

I am using the Requests Python library to make HTTP requests.

I was able to make a post request quietly in order to get a JWT token. But now I need to send this token through a header, but I have no idea how to do it.

The code I currently have is:

import requests

class Webservice(object):

    def __init__(self):
        self.authData = None

    def authenticate(self, username, password):

        credentials = {
            "username" : username,
            "password" : password
        }

        response = requests.post("http://exemplo/usuario/ajax-jwt-auth", data=credentials)

        data = response.json()

        if data.token:
            #guarda o token
            self.authData = data

        return response

    def getData(self):
        #preciso passar o token por um header nessa requisição
        return requests.get("http://exemplo/api/servicos")
    
asked by anonymous 27.10.2016 / 13:58

2 answers

1

You can use the requests-jwt package, which basically creates a authentication custom to be used with requests .

To install, type in the terminal:

pip install requests_jwt

Note : Requirements: requests and pyJWT

You can use it like this:

import requests
from requests_jwt import JWTAuth

class Webservice(object):
    def __init__(self):
        self.authData = None

    def authenticate(self, username, password):
        credentials = {
            "username" : username,
            "password" : password
        }
        # ...
        if data.token:
            #guarda o token
            self.authData = data.token

    def getData(self):
        auth = JWTAuth(self.authData)

        #preciso passar o token por um header nessa requisição
        return requests.get("http://exemplo/api/servicos", headers={'Authorization': auth})
        # Você também pode tentar usar...
        #return requests.get("http://exemplo/api/servicos", auth=auth) 
    
27.10.2016 / 22:25
2

The published response solves the problem well, but just as an addition I would like to say that you can also make use of JWT without installing a library.

Just set a header "Authorization" with the value "Bearer token_aqui" .

See:

headers = {
    "Authorization" : "Bearer %s" % token
}

return requests.get("http://example.com/api/results", headers=headers)
    
31.10.2016 / 16:55