Prerequisites
Before getting started, ensure you have completed the setup for Simple JWT
Background
In order to use the RSA algorithm, we need to have a private key and a public key. The private key is used during the signing process of generating the token. The public key is used to verify that the token is valid.
Step-by-Step Guide
1. Generate Private and Public Keys
openssl genpkey -algorithm RSA -out private.key -pkeyopt rsa_keygen_bits:2048
and
openssl rsa -pubout -in private.key -out public.key
2. Configure Django to Use the Keys
For local development, add environment variables SIGNING_KEY
and VERIFYING_KEY
in the .env file.
However, the key values contain newline characters, which are invalid in .env files. To fix this, convert the keys into a valid format before setting the values.
Example of the original key format:
-----BEGIN PRIVATE KEY-----
MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDtdRdOlG4bNyp7
...
-----END PRIVATE KEY-----
For example, in VSCode, enable Regex and find all \n
in the key value and replace it with \\n
After formatting:
Set the formatted keys in your .env file:
-
SIGNING_KEY
: Formatted private key -
VERIFYING_KEY
: Formatted public key
3. Update Django Settings
In your settings.py file, read the keys from the environment variables and replace the text \\n
with the actual newline character \n
:
SIGNING_KEY = env('SIGNING_KEY').replace("\\n", "\n")
VERIFYING_KEY = env('VERIFYING_KEY').replace("\\n", "\n")
4. Configure SIMPLE_JWT
Make sure to provide ALGORITHM
, SIGNING_KEY
and VERIFYING_KEY
in SIMPLE_JWT
in setting.py
SIMPLE_JWT = {
...
"ALGORITHM": "RS256",
"SIGNING_KEY": SIGNING_KEY,
"VERIFYING_KEY": VERIFYING_KEY
}
5. Install Cryptography Library
Make sure cryptography library is installed: Cryptographic Dependencies (Optional)
pip install djangorestframework-simplejwt[crypto]
Or, if you use Poetry
poetry add "djangorestframework-simplejwt[crypto]"
Top comments (0)