JWT Authentication class for python requests
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.