Boost FastAPI Security: OAuth2, JWT, RBAC, Refresh Tokens & MFA

This guide explains how to secure FastAPI applications using OAuth2 with JWT, role‑based access control, refresh‑token workflows, multi‑factor authentication, and integration with external providers such as Auth0, Keycloak, and Firebase.

Code Mala Tang
Code Mala Tang
Code Mala Tang
Boost FastAPI Security: OAuth2, JWT, RBAC, Refresh Tokens & MFA

Today we dive into practical techniques for strong security: refresh tokens, multi‑factor authentication (MFA), role‑based access control (RBAC), and connecting the application to external identity providers such as Auth0, Keycloak, and Firebase.

FastAPI natively supports OAuth2 and JWT (JSON Web Tokens). The standard flow is:

The user submits username and password to the /token endpoint using the OAuth2 password flow.

The application validates the credentials and returns a JWT access token.

Protected routes require the token in the Authorization: Bearer header.

FastAPI provides convenient classes such as OAuth2PasswordRequestForm to handle the login flow. With JWT you can encode user information and permissions directly in the token for stateless authentication.

Add Custom Role‑Based Permissions

RBAC lets you grant or restrict endpoint access based on user roles (e.g., admin, manager, user). To implement RBAC in FastAPI:

Add a roles field to the user model and encode it into the JWT.

Create a reusable dependency that extracts roles from the token and validates permissions.

Use this dependency to protect routes; raise an exception if the required role is missing.

Example implementation:

from fastapi import Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import jwt

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

def get_current_user_roles(token: str = Depends(oauth2_scheme)):
    payload = jwt.decode(token, "SECRET_KEY", algorithms=["HS256"])
    return payload.get("roles", [])

def require_roles(required_roles: list):
    def dependency(user_roles: list = Depends(get_current_user_roles)):
        if not set(user_roles).intersection(required_roles):
            raise HTTPException(status_code=403, detail="权限不足")
        return dependency
    return dependency

@app.get("/admin")
def admin_route(dep=Depends(require_roles(["admin"]))):
    return {"message": "你好,管理员!"}

This structure makes the API easier to extend for finer‑grained permissions.

Implement Refresh Tokens

Access tokens should have a short lifespan. To avoid frequent logins, issue a long‑lived refresh token that can request new access tokens.

Issue an access token and a refresh token at login.

Store the refresh token securely on the client and/or server (e.g., HTTP‑only cookie, blacklist).

Expose a /refresh endpoint to validate the refresh token and return a new access token.

Example implementation:

from fastapi_jwt_auth import AuthJWT

# 登录时发放令牌
access_token = Authorize.create_access_token(subject=user.username)
refresh_token = Authorize.create_refresh_token(subject=user.username)

# 刷新端点
@app.post('/refresh')
def refresh(Authorize: AuthJWT = Depends()):
    Authorize.jwt_refresh_token_required()
    current_user = Authorize.get_jwt_subject()
    new_access = Authorize.create_access_token(subject=current_user)
    return {"access_token": new_access}

For a secure refresh‑token mechanism, store the token in an HTTP‑only cookie and invalidate it on logout or compromise.

Use OTP and Authenticator Apps to Implement MFA

MFA adds an extra layer of security by requiring a one‑time password (OTP) generated by apps such as Google Authenticator or Authy after the initial login.

Typical MFA flow:

User logs in with username and password.

Server prompts the user to enter the OTP generated by their authenticator app.

Only after successful OTP verification is the user fully authenticated.

Example integration using pyotp:

import pyotp

# 用户注册时
otp_secret = pyotp.random_base32()
user.otp_secret = otp_secret

# 登录时:提示输入 OTP
totp = pyotp.TOTP(user.otp_secret)
if not totp.verify(entered_otp):
    raise HTTPException(status_code=400, detail="无效的 OTP")

All keys stored in the database should be encrypted, and strong password‑hashing algorithms must be used.

Integrate with Auth0, Keycloak, or Firebase

Auth0

Handles registration, login, and JWT issuance.

Redirect users to Auth0’s hosted login page, then verify Auth0‑issued tokens in FastAPI using libraries like Authlib or python‑jose.

Auth0 natively supports social login, MFA, and RBAC.

Keycloak

Self‑hosted identity and access management solution.

Integrate via fastapi-keycloak or generic OpenID Connect.

Provides built‑in RBAC, user management, and SSO.

Firebase

Google’s backend‑as‑a‑service for authentication.

Validate Firebase JWTs in FastAPI using the Firebase Admin SDK.

Protect routes by verifying the token in a FastAPI dependency.

SecureAuth FastAPI Sample Project

Suggested Directory Structure

/secureauth-fastapi/
├── app/
│   ├── main.py          # FastAPI application
│   ├── models.py        # User model
│   ├── auth.py          # Authentication and token logic
├── tests/
│   ├── test_auth.py
│   ├── test_rbac.py
├── requirements.txt
└── docs/
    └── README.md

Best Practices

Always hash passwords and never log sensitive data.

Store keys (JWT secret, OTP seeds) outside of source code.

Use environment variables for configuration.

Test both positive and negative scenarios (invalid or expired tokens).

Implement logging, alerts, and rate limiting on authentication endpoints.

By combining OAuth2 JWT, RBAC, refresh tokens, MFA, and external identity providers, you can deliver robust security for FastAPI applications without sacrificing development speed or user experience.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

AuthenticationJWTOAuth2FastAPIRBACRefresh tokenMFA
Code Mala Tang
Written by

Code Mala Tang

Read source code together, write articles together, and enjoy spicy hot pot together.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.