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

Asked

Viewed 836 times

5

I’m using the library Requests Python to make HTTP requests.

I was able to post a request quietly in order to obtain 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")

2 answers

2

The published answer solves the problems well, but just as an addition I would like to say that it is also possible to make use of JWT without installing a library.

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

Behold:

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

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

1


You can use the package requests-jwt, which basically creates a mechanism customized authentication 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) 

Browser other questions tagged

You are not signed in. Login or sign up in order to post.