Performance: JWT token verification
This affects the server response time and user interaction speed by adding cryptographic verification during API requests.
from fastapi import Depends, HTTPException from fastapi.security import OAuth2PasswordBearer import jwt import asyncio oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def verify_token(token: str = Depends(oauth2_scheme)): loop = asyncio.get_running_loop() try: payload = await loop.run_in_executor(None, jwt.decode, token, "secret", algorithms=["HS256"]) except jwt.PyJWTError: raise HTTPException(status_code=401, detail="Invalid token") return payload
from fastapi import Depends, HTTPException from fastapi.security import OAuth2PasswordBearer import jwt oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") async def verify_token(token: str = Depends(oauth2_scheme)): try: payload = jwt.decode(token, "secret", algorithms=["HS256"]) except jwt.PyJWTError: raise HTTPException(status_code=401, detail="Invalid token") return payload
| Pattern | CPU Blocking | Event Loop Impact | Response Latency | Verdict |
|---|---|---|---|---|
| Synchronous JWT decode on main thread | High | Blocks event loop | Increases by 10-30ms | [X] Bad |
| Asynchronous JWT decode offloaded to executor | Low | Non-blocking | Minimal increase | [OK] Good |
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
return payloadfrom fastapi import Depends, HTTPException
from jose import jwt, JWTError
def verify_token(token: str):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
except:
HTTPException(status_code=401, detail="Invalid token")
return payloadPass the test and this pattern moves unknown