📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials FastAPI JWT Authentication FastAPI

JWT Authentication FastAPI

6 min read Quiz at the end
Implement OAuth2 password flow: token endpoint, JWT creation, and current_user dependency.

JWT Authentication

pip install python-jose[cryptography] passlib[bcrypt]

from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from jose import JWTError, jwt
from passlib.context import CryptContext
from datetime import timedelta

pwd_context   = CryptContext(schemes=["bcrypt"], deprecated="auto")
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")

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

def create_token(data: dict, expires_delta: timedelta) -> str:
    to_encode = data.copy()
    to_encode["exp"] = datetime.utcnow() + expires_delta
    return jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)

@app.post("/token")
def login(form: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    user = db.query(User).filter(User.email == form.username).first()
    if not user or not pwd_context.verify(form.password, user.hashed_password):
        raise HTTPException(status_code=401, detail="Invalid credentials")
    token = create_token({"sub": str(user.id)}, timedelta(hours=1))
    return {"access_token": token, "token_type": "bearer"}
Topic Quiz · 1 questions

Test your understanding before moving on

1. What does @jwt_required() do in FastAPI?
💡 jwt_required validates the Bearer token and raises 401 if invalid or missing.