Jurrian Tromp
Deep into Django

Follow

Deep into Django

Follow

JWT Authentication class for python requests

Jurrian Tromp's photo
Jurrian Tromp
·Mar 13, 2023

When using the requests library in Python you can use some built-in auth mechanisms like HTTPBasicAuth and HTTPDigestAuth. However, I could not find any package that allows doing a simple JSON Web Token (JWT) authentication, so I decided to make a snippet.

jwt_auth = JWTAuth(
    auth_url='https://endpoint.example/api/v1/auth',
    api_payload={
        'api_key': '<API_KEY>',
        'api_secret': '<API_SECRET>',
    }
)
# Using it directly
requests.get('some-url', auth=jwt_auth)

# Or when applied to a session for all requests:
session = requests.Session()
session.auth = jwt_auth

JWTAuth needs to know your auth_url and api_payload to be able to authenticate with the server on your first request. It will only work when you receive back an access and refresh token. Based on your situation and API response, you might need to change this a little to make it work.

 
Share this