✅ FastAPI JWT Token Authentication with Full Access and One-Time Refresh Token

Posted by

FastAPI JWT Token Auth

FastAPI JWT Token Auth

FastAPI is a modern web framework for building APIs with Python. JWT (JSON Web Tokens) is a popular method for securely transmitting information between parties as a JSON object. In this article, we will discuss how to implement JWT token authentication in FastAPI with full access and a one-time refresh token.

Setting Up FastAPI and JWT Token Auth

To get started with FastAPI and JWT token authentication, you will need to install the necessary libraries. You can do this using pip:

pip install fastapi
pip install pyjwt

Next, you can create a new FastAPI app and set up JWT token authentication. Here is a basic example:


from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
import jwt
from jwt.exceptions import DecodeError
from datetime import datetime, timedelta

app = FastAPI()

JWT_SECRET = "mysecret"
ACCESS_TOKEN_EXPIRE_MINUTES = 30

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def create_access_token(data: dict):
    to_encode = data.copy()
    expire = datetime.utcnow() + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
    to_encode.update({"exp": expire})
    encoded_jwt = jwt.encode(to_encode, JWT_SECRET, algorithm='HS256')
    return encoded_jwt

@app.post("/token")
def login(form_data: OAuth2PasswordRequestForm = Depends()):
    user = authenticate_user(form_data.username, form_data.password)
    if user is None:
        raise HTTPException(status_code=400, detail="Incorrect username or password")
    access_token = create_access_token(data={"sub": user.username})
    return {"access_token": access_token, "token_type": "bearer"}

@app.get("/protected")
def protected_route(token: str = Depends(oauth2_scheme)):
    try:
        payload = jwt.decode(token, JWT_SECRET, algorithms=["HS256"])
        user = get_user_from_db(payload["sub"])
        return {"message": "Welcome, {}".format(user.username)}
    except DecodeError:
        raise HTTPException(status_code=401, detail="Invalid token")

Full Access Token and One-Time Refresh Token

In the code above, we have implemented a basic JWT token authentication system with FastAPI. The access token is set to expire after a certain time specified in minutes. However, to provide a seamless user experience, you can also implement a one-time refresh token for continuous access.

With a one-time refresh token, users can obtain a new access token without having to log in again. This can be achieved by creating a separate endpoint for refreshing tokens:


@app.post("/refresh")
def refresh_token(refresh_token: str):
    try:
        payload = jwt.decode(refresh_token, JWT_SECRET, algorithms=["HS256"])
        user = get_user_from_db(payload["sub"])
        new_access_token = create_access_token(data={"sub": user.username})
        return {"access_token": new_access_token, "token_type": "bearer"}
    except DecodeError:
        raise HTTPException(status_code=401, detail="Invalid token")

With this setup, users can use the refresh token to obtain new access tokens indefinitely, as long as the refresh token remains valid. This provides a secure and convenient way to manage user authentication in FastAPI.

Conclusion

FastAPI is a powerful framework for building APIs, and implementing JWT token authentication can enhance the security and user experience of your applications. By using a combination of full access and one-time refresh tokens, you can provide users with secure and continuous access to your API endpoints.

0 0 votes
Article Rating
7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
@anonlo22
8 months ago

Thank you Men, your code is clean and easy to understand.

@ahmadumar9387
8 months ago

love your topics many thanks

@umarr6104
8 months ago

Nice content

@ashishjohn9708
8 months ago

Thanks
Can you please share logout endpoint, you are using jwt and refresh token how would you create logout endpoint?

@user-ve4fu1gd7t
8 months ago

23-12-2023 i start today i will finish this playlist , thanks for your help

@nelotechechnologies
8 months ago

Always a life saver❤

@Mistery28543
8 months ago

Nice video! I have been looking for a video about this