
FastAPI
JSON Web Tokens (JWT) are stateless, self-contained tokens ideal for scalable authentication. They include user claims and can be verified without database lookups.
JWTs consist of three parts separated by dots: header.payload.signature
from fastapi import FastAPI, HTTPException
from datetime import datetime, timedelta
from jose import JWTError, jwt
from pydantic import BaseModel
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
class Token(BaseModel):
access_token: str
token_type: str
@app.post("/token")
async def login(username: str, password: str):
# Validate credentials
if not verify_password(username, password):
raise HTTPException(status_code=401, detail="Invalid credentials")
# Create token
token = jwt.encode(
{"sub": username, "exp": datetime.utcnow() + timedelta(hours=1)},
SECRET_KEY,
algorithm=ALGORITHM
)
return {"access_token": token, "token_type": "bearer"}from fastapi.security import HTTPBearer, HTTPAuthenticationCredentials
security = HTTPBearer()
async def get_current_user(credentials: HTTPAuthenticationCredentials = Depends(security)):
token = credentials.credentials
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username = payload.get("sub")
if not username:
raise HTTPException(status_code=401, detail="Invalid token")
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
return {"username": username}
@app.get("/protected")
async def protected(user: dict = Depends(get_current_user)):
return {"user": user}from datetime import datetime, timedelta
def create_access_token(data: dict, expires_delta: timedelta = None):
to_encode = data.copy()
if expires_delta:
expire = datetime.utcnow() + expires_delta
else:
expire = datetime.utcnow() + timedelta(minutes=15)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwtJWT is ideal for:
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward