Performance: OAuth2 password flow
This affects the server response time and initial page load speed when authenticating users via password flow.
Jump into concepts and practice - no test required
from fastapi import FastAPI, Depends, HTTPException from fastapi.security import OAuth2PasswordRequestForm import asyncio app = FastAPI() async def authenticate_user_async(username: str, password: str): await asyncio.sleep(0) # simulate async DB call # actual async DB call here return True # or user object @app.post('/token') async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = await authenticate_user_async(form_data.username, form_data.password) if not user: raise HTTPException(status_code=400, detail='Incorrect username or password') token = create_access_token(user) return {'access_token': token, 'token_type': 'bearer'}
from fastapi import FastAPI, Depends, HTTPException from fastapi.security import OAuth2PasswordRequestForm app = FastAPI() @app.post('/token') async def login(form_data: OAuth2PasswordRequestForm = Depends()): user = authenticate_user(form_data.username, form_data.password) # synchronous blocking call if not user: raise HTTPException(status_code=400, detail='Incorrect username or password') token = create_access_token(user) return {'access_token': token, 'token_type': 'bearer'}
| Pattern | Server Blocking | Event Loop Impact | Response Time | Verdict |
|---|---|---|---|---|
| Synchronous authentication | Blocks server thread | Blocks event loop | High latency | [X] Bad |
| Asynchronous authentication | Non-blocking | Event loop free | Low latency | [OK] Good |
from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
if form_data.username == 'alice' and form_data.password == 'secret':
return {'access_token': 'token123', 'token_type': 'bearer'}
return {'error': 'Invalid credentials'}from fastapi import FastAPI, Depends
from fastapi.security import OAuth2PasswordRequestForm
app = FastAPI()
@app.post('/token')
async def login(form_data: OAuth2PasswordRequestForm):
if form_data.username == 'bob' and form_data.password == 'pass':
return {'access_token': 'abc', 'token_type': 'bearer'}
return {'error': 'Invalid'}from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer
app = FastAPI()
oauth2_scheme = OAuth2PasswordBearer(tokenUrl='token')
def verify_token(token: str):
if token != 'validtoken':
raise HTTPException(status_code=401, detail='Invalid token')
@app.get('/secure-data')
async def secure_data(token: str = Depends(oauth2_scheme)):
verify_token(token)
return {'data': 'secret info'}