Skip to main content

Command Palette

Search for a command to run...

Activity 46: Documentation of Python JWT

Published
3 min read

Activity 46: Documentation of Python JWT

In this activity, we'll document how to work with JSON Web Tokens (JWT) in Python using the PyJWT library. JWT is widely used for securely transmitting information between parties, especially in web applications for user authentication and authorization.

What is JWT?

A JSON Web Token (JWT) is an open standard 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 key (HMAC) or a public/private key pair using RSA or ECDSA.

A JWT consists of three parts:

  1. Header: Contains metadata about the token, like the signing algorithm.

  2. Payload: Contains the claims or the information you want to transmit.

  3. Signature: Used to verify the integrity of the token and that it was issued by a trusted source.

  • Header: Typically includes the type of token (JWT) and the signing algorithm, such as HMAC SHA256 or RSA.

  • Payload: Contains the claims (data). Claims can be of three types:

    • Registered claims: Predefined claims such as sub (subject), iat (issued at), exp (expiration time), etc.

    • Public claims: Claims defined by the application.

    • Private claims: Custom claims that are shared between the issuer and the consumer of the token.

  • Signature: To create the signature part you have to take the encoded header, the encoded payload, a secret key, and the algorithm specified in the header.

Steps to Implement JWT in Python using Flask

Step 1: Install the Required Libraries

To work with JWT in Python, you need the Flask and PyJWT libraries. You can install them using pip:

pip install Flask pyjwt

Step 2: Generate JWT Token

The JWT token can be generated using the jwt.encode() method in PyJWT. Here’s an example of how to create a token:

import bcrypt

# Hashing a password
password = b"mysecretpassword"
hashed = bcrypt.hashpw(password, bcrypt.gensalt())

# Verifying the password
if bcrypt.checkpw(password, hashed):
 print("Password is correct")
else:
 print("Password is incorrect")
import hashlib

# Input data
data = "Hello, world!"

# Create a SHA-256 hash object
hash_object = hashlib.sha256()

# Update the hash object with the data (needs to be encoded to bytes)
hash_object.update(data.encode('utf-8'))

# Get the hexadecimal representation of the hash
hash_value = hash_object.hexdigest()

print(f"SHA-256 hash of '{data}': {hash_value}")
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Hello Page</title>
</head>
<body>
    <h1>{{ message }}</h1>
</body>
</html>

Explanation of Flask Routes:

  1. GET /get-jwt:

    • This endpoint generates a JWT token for a specified username. The username is passed as a query parameter. If the username exists, a token is generated and returned to the client.
  2. POST /login:

    • This endpoint authenticates the user. It takes a JSON object with username and password, checks them against the in-memory users dictionary, and if valid, generates a JWT token and sends it back to the client.
  3. GET /validate-token:

    • This endpoint checks if a provided JWT token is valid by decoding it with the secret key. The token is expected to be sent in the Authorization header of the request.

Step 5: Testing the Application

  • Register a user: Simulate registering a user by adding a username and password to the users dictionary.

  • Login: Use the /login route to log in and get a JWT token.

  • Validate Token: Send the token received from login to the /validate-token route to verify if it is valid.