igorbenav / FastAPI-boilerplate

An extendable async API using FastAPI, Pydantic V2, SQLAlchemy 2.0, PostgreSQL and Redis.
MIT License
589 stars 69 forks source link

Token refresh #63

Closed igorbenav closed 10 months ago

igorbenav commented 10 months ago

🔐JWT Authentication With Refresh Token

Details

The JWT in the boilerplate was updated to work in the following way:

  1. JWT Access Tokens: how you actually access protected resources is passing this token in the request header.
  2. Refresh Tokens: you use this type of token to get an access token, which you'll use to access protected resources.

The access token is short lived (default 30 minutes) to reduce the damage of a potential leak. The refresh token, on the other hand, is long lived (default 7 days), and you use it to renew your access token without the need to provide username and password every time it expires.

Since the refresh token lasts for a longer time, it's stored as a cookie in a secure way:

# app/api/v1/login

...
response.set_cookie(
    key="refresh_token",
    value=refresh_token,
    httponly=True,               # Prevent access through JavaScript
    secure=True,                 # Ensure cookie is sent over HTTPS only
    samesite='Lax',              # Default to Lax for reasonable balance between security and usability
    max_age=<number_of_seconds>  # Set a max age for the cookie
)
...

You may change it to suit your needs. The possible options for samesite are:

🚀Usage

What you should do with the client is:

This authentication setup in the provides a robust, secure, and user-friendly way to handle user sessions in your API applications.