FastAPI JWT Authentication Middleware
Implement JWT authentication in FastAPI with python-jose and passlib. Includes token generation, verification middleware, password hashing with bcrypt, and.
Code
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}