Expert skill for implementing JWT-based authentication in FastAPI applications. Handles token generation, verification, user authentication, protected routes, and security best practices. Includes setup for password hashing, OAuth2 schemes, and user data isolation. Use when implementing JWT authentication in FastAPI applications, securing API endpoints with token-based authentication, or implementing user registration and login functionality.
Dependency Installation
pyjwt, pwdlib[argon2], and other required packagesUser Model and Database Setup
JWT Token Generation
Authentication Endpoints
/token endpoint for loginSecurity Implementation
After activation, I will deliver:
User says: "I need to add JWT authentication to my FastAPI application."
This Skill Instantly Activates → Delivers:
pyjwt and pwdlibUser says: "Secure my API endpoints with JWT tokens in FastAPI."
This Skill Responds: → Sets up OAuth2PasswordBearer security scheme → Creates token generation endpoint → Implements JWT verification middleware → Provides protected route examples with user isolation
pip install pyjwt pwdlib[argon2]
from pwdlib import PasswordHash
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from pydantic import BaseModel
password_hash = PasswordHash.recommended()
def hash_password(password: str):
return password_hash.hash(password)
def verify_password(password: str, hashed_password: str):
return password_hash.verify(password, hashed_password)
from datetime import datetime, timedelta
import jwt
SECRET_KEY = "your-secret-key" # Use environment variable
ALGORITHM = "HS256"
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
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
@app.post("/token")
async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]):
user = fake_users_db.get(form_data.username)
if not user or not verify_password(form_data.password, user["hashed_password"]):
raise HTTPException(status_code=400, detail="Incorrect username or password")
access_token_expires = timedelta(minutes=30)
access_token = create_access_token(
data={"sub": user["username"]}, expires_delta=access_token_expires
)
return {"access_token": access_token, "token_type": "bearer"}
async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)]):
credentials_exception = HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Could not validate credentials",
headers={"WWW-Authenticate": "Bearer"},
)
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise credentials_exception
except jwt.PyJWTError:
raise credentials_exception
user = get_user(username=username)
if user is None:
raise credentials_exception
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
npx skills add MuhammedSuhaib/fastapi-jwt-auth下载完整 Skill 目录,包含 SKILL.md 及所有相关文件
Search for places (restaurants, cafes, etc.) via Google Places API proxy on localhost.
Interact with GitHub using the `gh` CLI. Use `gh issue`, `gh pr`, `gh run`, and `gh api` for issues, PRs, CI runs, and advanced queries.
Create or update AgentSkills. Use when designing, structuring, or packaging skills with scripts, references, and assets.
Start voice calls via the OpenClaw voice-call plugin.
Notion API for creating and managing pages, databases, and blocks.
Gemini CLI for one-shot Q&A, summaries, and generation.
Category:developer