Integrate Hanko with Python backend
Get the Hanko API URL
Retrieve the API URL from the Hanko console.
If you are self-hosting Hanko you need to provide your own URL.
Hanko Authentication with JWT
Upon a successful login, Hanko sends a cookie containing a JSON Web Token (JWT). You can use this JWT to authenticate requests on your backend.
Steps to Authenticate Requests
-
Retrieve the JSON Web Key Set (JWKS): The JWKS has the public keys to verify the JWT. Fetch it from the Hanko API’s
.well-known/jwks.json
endpoint. -
Verify the JWT: Use the JWKS to verify the JWT.
Python-based Backend Examples
Below we show examples of using a custom middleware in FastAPI, Django and Flask, based backend using the PyJWT package.
Since you will be decoding the token using the RSA digital signature algorithm, you will need to install the cryptography library. You can install this library either directly or as an additional requirement within the PyJWT package.
The pyjwt[crypto]
format is recommended in requirements files in projects using PyJWT, as a separate cryptography requirement line may later be mistaken for an unused requirement and removed.
While using PyJWT to decode JWTs, you might encounter errors such as binascii.Error: Incorrect padding
and jwt.exceptions.DecodeError: Invalid crypto padding
. These errors often occur due to insufficient base64
padding at the end of the token.
To resolve this, you might need to manually add the necessary padding to the token before attempting to decode it. You can read the token as a string and append the required padding characters to ensure successful decoding.