How To Create A JWT Authentication In Django

JWT authentication module in Django using the PyJWT library:

Step 1: Install the PyJWT library You can install the library using pip by running the following command in your virtual environment:

				
					pip install PyJWT
				
			

Step 2: Create the JWT authentication module Create a new file called jwt_auth_module.py with the following contents:

				
					import jwt
from datetime import datetime, timedelta

class JWTAuthModule:
    def __init__(self, secret_key, expiration_time):
        self.secret_key = secret_key
        self.expiration_time = expiration_time

    def generate_token(self, user_id):
        payload = {
            'user_id': user_id,
            'exp': datetime.utcnow() + timedelta(seconds=self.expiration_time)
        }

        token = jwt.encode(payload, self.secret_key, algorithm='HS256')
        return token.decode('utf-8')

    def validate_token(self, token):
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
            return True
        except jwt.ExpiredSignatureError:
            return False
        except jwt.InvalidTokenError:
            return False

    def get_user_id_from_token(self, token):
        try:
            payload = jwt.decode(token, self.secret_key, algorithms=['HS256'])
            return payload['user_id']
        except (jwt.ExpiredSignatureError, jwt.InvalidTokenError, KeyError):
            return None
				
			

Step 3: Using the JWT authentication module You can use the JWTAuthModule class to generate and validate JWT tokens. Here’s an example of how you can use it:

				
					from jwt_auth_module import JWTAuthModule

jwt_auth = JWTAuthModule(secret_key='your-secret-key', expiration_time=3600)

# Generate a token for a user ID
user_id = 1
token = jwt_auth.generate_token(user_id)
print("Generated token:", token)

# Validate a token
is_valid = jwt_auth.validate_token(token)
print("Is valid token:", is_valid)

# Get the user ID from a token
user_id = jwt_auth.get_user_id_from_token(token)
print("User ID from token:", user_id)
				
			

In this example, the generate_token method generates a JWT token based on a user ID. The validate_token method checks if a token is valid and not expired. The get_user_id_from_token method extracts the user ID from a token.

Please note that this is a basic example, and you may need to customize it further based on your specific requirements, such as adding additional claims, handling token storage, and integrating it with your authentication workflow.