DEV Community

Jen C.
Jen C.

Posted on

Django REST Framework with Simple JWT (JSON Web Token): Steps on how to sign and verify using the RSA algorithm

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
Enter fullscreen mode Exit fullscreen mode

and

openssl rsa -pubout -in private.key -out public.key
Enter fullscreen mode Exit fullscreen mode

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-----
Enter fullscreen mode Exit fullscreen mode

For example, in VSCode, enable Regex and find all \n in the key value and replace it with \\n

Image description

After formatting:

Image des cription

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")
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

5. Install Cryptography Library

Make sure cryptography library is installed: Cryptographic Dependencies (Optional)

pip install djangorestframework-simplejwt[crypto]
Enter fullscreen mode Exit fullscreen mode

Or, if you use Poetry

poetry add "djangorestframework-simplejwt[crypto]"
Enter fullscreen mode Exit fullscreen mode

Image of Quadratic

Cursor for data analysis

The AI spreadsheet where you can do complex data analysis with natural language.

Try Quadratic free

Top comments (0)

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

👋 Kindness is contagious

If this post resonated with you, feel free to hit ❤️ or leave a quick comment to share your thoughts!

Okay