Skip to main content

Command Palette

Search for a command to run...

JWT Authentication class for python requests

Updated
J

Made my first website in Microsoft Word at age 13, when I discovered the "save as html" button. Since then I've journeyed various computing languages, eventually settling for Python. I love diving into the core of my favorite framework - Django - discover and writing about new stuff.

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.

Deep into Django

Part 6 of 9

Django offers a great deal of hidden functionality - secret gems - if you know where to look. In this serie I am showing tips and tricks to get the most out of Django.

Up next

Reducing queries for ForeignKeys in Django admin inlines

Use 93x less queries using patched raw_id_fields and prefetching

More from this blog

D

Deep into Django

9 posts

I love diving into the core of my favorite framework - Django - discovering and writing about new tech stuff.

JWT Authentication class for python requests