FastAPI JWT Authentication Middleware

Implement JWT authentication in FastAPI with python-jose and passlib. Includes token generation, verification middleware, password hashing with bcrypt, and.

PythonFastapiAuth Jwt

Code

snippet
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
from jose import jwt, JWTError
from datetime import datetime, timedelta

SECRET_KEY = 'your-secret-key'
ALGORITHM = 'HS256'

app = FastAPI()
oauth2 = OAuth2PasswordBearer(tokenUrl='token')

def create_token(data: dict) -> str:
    payload = data.copy()
    payload['exp'] = datetime.utcnow() + timedelta(hours=1)
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

async def get_current_user(token: str = Depends(oauth2)):
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except JWTError:
        raise HTTPException(401, 'Invalid token')

@app.get('/protected')
async def protected(user = Depends(get_current_user)):
    return {'user': user}

What the code does

FastAPI JWT Authentication Middleware keeps everything in the functions create_token, get_current_user and protected.

Asynchronous boundaries use await, so failures surface as exceptions at the call site rather than being swallowed. FastAPI, Depends, HTTPException, OAuth2PasswordBearer, jwt are the only symbols borrowed from fastapi — the coupling is explicit and narrow. HTTPException appears at a raise inside an except handler — it fires only while that failure type is already being handled.

It builds and returns a fresh value rather than reusing its inputs.

What to watch for

  • Dependency check: fastapi and jose — not built-in, must be present in the project.

Applying it

The primary signature is def create_token(data: dict) -> str

Import create_token from the file and call it — the rest of the code is implementation detail.

Statements that matter

return {'user': user}
async def get_current_user(token: str = Depends(oauth2)):
    try:
        return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
    except JWTError:
        raise HTTPException(401, 'Invalid token')
def create_token(data: dict) -> str:
    payload = data.copy()
    payload['exp'] = datetime.utcnow() + timedelta(hours=1)
    return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)

Interactive Tools for This Topic

FAQ

Does `create_token` modify its input?
No. Nothing passed in is written to, which makes the call safe on shared data.
When is the exception raised?
Inside an `except` handler — the `HTTPException` fires only while that failure type is already being handled, not on its own trigger.
Does this require external packages?
Yes — `fastapi` and `jose`. Add them to your project before running the snippet.