Thursday, December 26, 2024
Google search engine
HomeLanguagesHow to Generate JWT Tokens using FastAPI in Python

How to Generate JWT Tokens using FastAPI in Python

In this article, we will see how to create and validate a JWT in the FastAPI framework. This is a very basic example of how to create and validate the tokens, this is just for reference, and using this approach one can easily create JWT according to the need and use it accordingly while validation. A simple example of this can be the implementation of the SSO feature in web applications. we will create signed JSON web tokens in FastAPI. This article will be covered in following subtopics:

  • What are JWTs and when to use JWTs 
  • Necessary installations.
  • Creating and using JWT in fastapi.

What are JWTs and when to use JWTs?

JSON Web Token (JWT) is an open standard (RFC7519) which is used to define a secure way for transforming information between two parties. The information/message/data is digitally signed using private or public keys when it is shared using JWT.

The most common scenario for using JWTs is Authorization. Suppose we want to implement a Single Sign On(SSO) feature in our website which allows the user to access different domains without asking him to sign in every time. Once the user is signed in, each subsequent request will include the JWT, allowing the user to access routes, services, and resources that are permitted with that token.

Required Packages

First of all create a folder in your system for this project and after that install FastAPI, uvicorn and python-jose to generate and verify the JWT tokens in Python. Use these commands to install these packages.

pip install fastapi
pip install uvicorn
pip install python-jose

After successful installation of these libraries, we can easily create out JWT and test it with FastAPI.

Creating and Using JWT in FastAPI

Step 1: In your project directory create a file called main.py

Step 2: Open your terminal and write the command given below, this will give you a secret key which we will use in our main.py code.

openssl rand -hex 32

Note: If you don’t have OpenSSL installed, you can get it installed from https://wiki.openssl.org/index.php/Binaries.

Step 4: Once you have your secret key, copy and paste it into the SECRET_KEY section in the following code to the main.py file.

Python3




# import libraries
from fastapi import FastAPI, status, HTTPException
from jose import JWTError, jwt
from pydantic import BaseModel
from datetime import datetime, timedelta
 
# replace it with your 32 bit secret key
SECRET_KEY = "09d25e094faa****************f7099f6f0f4caa6cf63b88e8d3e7"
 
# encryption algorithm
ALGORITHM = "HS256"
 
# Pydantic Model that will be used in the
# token endpoint for the response
class Token(BaseModel):
    access_token: str
    token_type: str
 
 
# Initialise the app
app = FastAPI()
 
# this function will create the token
# for particular data
def create_access_token(data: dict):
    to_encode = data.copy()
     
    # expire time of the token
    expire = datetime.utcnow() + timedelta(minutes=15)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
     
    # return the generated token
    return encoded_jwt
 
# the endpoint to get the token
@app.get("/get_token")
async def get_token():
   
    # data to be signed using token
    data = {
        'info': 'secret information',
        'from': 'GFG'
    }
    token = create_access_token(data=data)
    return {'token': token}
 
# the endpoint to verify the token
@app.post("/verify_token")
async def verify_token(token: str):
    try:
        # try to decode the token, it will
        # raise error if the token is not correct
        payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
        return payload
    except JWTError:
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail="Could not validate credentials",
        )


Step 5: Once you have saved the file, go to the terminal and run the application using this command : 

uvicorn main:app --reload

Output:

You should get the “Application startup complete” response on the terminal like this :

 

Now, in your browser go to http://localhost:8000/docs. You should see the FastAPI swagger UI : 

 

Click on “/get_token” and then click on “Try it Out” and then “Execute”. You will the response from the server below that tab. If everything works well you can have the token generated like this :

 

You can now copy this token and go to the second endpoint “/verify_token”, click on “Try it out”, paste the token and execute it in the same way as you executed the previous endpoint. You will see the following screen : 

 

This response is for a valid token, now try to change the token and execute it again. You will now see the exception saying that “could not validate credentials”.

 

RELATED ARTICLES

Most Popular

Recent Comments