How to generate jwt token using Python.

Free Python Code - Sep 6 '23 - - Dev Community

Hi 🙂🖐

In this post, I will share with How to generate jwt token using Python.

JSON Web Token (JWT) is an open standard (RFC 7519) that defines a compact and self-contained way for securely transmitting information between parties as a JSON object. This information can be verified and trusted because it is digitally signed. JWTs can be signed using a secret (with the HMAC algorithm) or a public/private key pair using RSA or ECDSA.

Although JWTs can be encrypted to also provide secrecy between parties, we will focus on signed tokens. Signed tokens can verify the integrity of the claims contained within it, while encrypted tokens hide those claims from other parties. When tokens are signed using public/private key pairs, the signature also certifies that only the party holding the private key is the one that signed it.

https://jwt.io/introduction

To generate jwt tokens in python you need to install PyJWT from pip install PyJWTand install python-dotenv

Now you need to create .env file to store the secret key and algorithm name.

generate secret token using secrtes lib in python

import secrets

print(secrets.token_hex(20)) 
# 381836fe163039ab7bcd0a84bf54dded9fbd4269
Enter fullscreen mode Exit fullscreen mode

.env file content

secret = 381836fe163039ab7bcd0a84bf54dded9fbd4269
algorithm = HS256
Enter fullscreen mode Exit fullscreen mode

Import modules

import jwt
import time
import os
import dotenv
from datetime import timedelta, datetime, timezone
Enter fullscreen mode Exit fullscreen mode

Load env values

dotenv.load_dotenv()

secret = os.getenv('secret')
algorithm = os.getenv('algorithm')
Enter fullscreen mode Exit fullscreen mode

Create the payload
exp is the expiration date. I will to make it expire after 20 seconds to test it. 🤗

payload = {
    'user_id': "111r23qw12rq12rqw1",
    'exp': datetime.now(timezone.utc) + timedelta(seconds=20)
}

token = jwt.encode(payload, secret, algorithm)
Enter fullscreen mode Exit fullscreen mode

decode the token

print(jwt.decode(token, secret, algorithm))
Enter fullscreen mode Exit fullscreen mode

result

{'user_id': '111r23qw12rq12rqw1', 'exp': 1694010686}
Enter fullscreen mode Exit fullscreen mode

Check if my code really works.  🙃
use time.sleep(20)

import jwt
import time
import os
import dotenv
from datetime import timedelta, datetime, timezone

dotenv.load_dotenv()

secret = os.getenv('secret')
algorithm = os.getenv('algorithm')

payload = {
    'user_id': "111r23qw12rq12rqw1",
    'exp': datetime.now(timezone.utc) + timedelta(seconds=20)
}

token = jwt.encode(payload, secret, algorithm)

time.sleep(20)

print(jwt.decode(token, secret, algorithm))
Enter fullscreen mode Exit fullscreen mode

result

  raise ExpiredSignatureError("Signature has expired")
jwt.exceptions.ExpiredSignatureError: Signature has expired
Enter fullscreen mode Exit fullscreen mode

It's works.😎 This error because the token has expired. You can use try and except to handle this error.


import jwt
import time
import os
import dotenv
from datetime import timedelta, datetime, timezone

dotenv.load_dotenv()

secret = os.getenv('secret')
algorithm = os.getenv('algorithm')

payload = {
    'user_id': "111r23qw12rq12rqw1",
    'exp': datetime.now(timezone.utc) + timedelta(seconds=20)
}

token = jwt.encode(payload, secret, algorithm)

time.sleep(20)

try:
    if jwt.decode(token, secret, algorithm):
        print('welcome')
except Exception as e:
    print(e)
Enter fullscreen mode Exit fullscreen mode

Create function for generate jwt token and decode

import jwt
import time
import os
import dotenv
from datetime import timedelta, datetime, timezone

dotenv.load_dotenv()

secret = os.getenv('secret')
algorithm = os.getenv('algorithm')


def create_jwt_token(user_id, exp = 7):
    payload = {
        'user_id': user_id,
        'exp': datetime.now(timezone.utc) + timedelta(seconds=exp)
    }

    token = jwt.encode(payload, secret, algorithm)
    return token

def decode_jwt_token(token):
    is_decoded = False
    try:
        user_id = jwt.decode(token, secret, algorithm)['user_id']
        if user_id:
            is_decoded = True

        return is_decoded
    except:
        return is_decoded


token = create_jwt_token('123faafsafsfasfs', 7)
print(decode_jwt_token(token)) # True
Enter fullscreen mode Exit fullscreen mode

If you add time.sleep(7)

token = create_jwt_token('123faafsafsfasfs', 7)
time.sleep(7)
print(decode_jwt_token(token)) # False
Enter fullscreen mode Exit fullscreen mode

This is a very simple example of how to generate a JWT token.

Now we're done 🤗

Don't forget to like and follow 🙂

Support me on PayPal 🤗
https://www.paypal.com/paypalme/amr396

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .