Ojasa Mirai

Ojasa Mirai

FastAPI

Loading...

Learning Level

🟢 Beginner🔵 Advanced
🚀 Authentication Basics📚 API Keys📚 Basic Auth📚 JWT Tokens📚 OAuth2📚 Scopes📚 Securing Endpoints📚 Token Refresh📚 Role-Based Access
Fastapi/Authentication/Jwt Tokens

JWT Token Authentication

JSON Web Tokens (JWT) are stateless, self-contained tokens ideal for scalable authentication. They include user claims and can be verified without database lookups.

How JWT Works

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"}

Verifying JWT Tokens

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}

Token Expiration

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_jwt

Common Patterns and Best Practices

  • ✅ Use strong, random secret keys
  • ✅ Set reasonable token expiration times
  • ✅ Implement refresh token rotation
  • ✅ Store tokens securely on client
  • ✅ Use HTTPS for all JWT transmission
  • ✅ Validate token signature
  • ✅ Check token expiration
  • ✅ Implement token revocation if needed

Real-World Usage

JWT is ideal for:

  • Single-page applications (SPAs)
  • Mobile apps
  • Microservices
  • Cross-domain authentication
  • API rate limiting per user

Resources

Python Docs

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

Courses

PythonFastapiReactJSCloud

© 2026 Ojasa Mirai. All rights reserved.

TwitterGitHubLinkedIn