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.
About the author
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.
Comments
Join the discussionNo comments yet. Be the first to comment.
Deep into Django
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.