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.
To generate jwt tokens in python you need to install PyJWT from pip install PyJWT
and 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
.env file content
secret = 381836fe163039ab7bcd0a84bf54dded9fbd4269
algorithm = HS256
Import modules
import jwt
import time
import os
import dotenv
from datetime import timedelta, datetime, timezone
Load env values
dotenv.load_dotenv()
secret = os.getenv('secret')
algorithm = os.getenv('algorithm')
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)
decode the token
print(jwt.decode(token, secret, algorithm))
result
{'user_id': '111r23qw12rq12rqw1', 'exp': 1694010686}
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))
result
raise ExpiredSignatureError("Signature has expired")
jwt.exceptions.ExpiredSignatureError: Signature has expired
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)
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
If you add time.sleep(7)
token = create_jwt_token('123faafsafsfasfs', 7)
time.sleep(7)
print(decode_jwt_token(token)) # False
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