OAuth2 password flow lets users log in by giving their username and password directly to your app. It helps your app get a token to access protected data safely.
OAuth2 password flow in FastAPI
from fastapi import FastAPI, Depends from fastapi.security import OAuth2PasswordRequestForm app = FastAPI() @app.post('/token') async def login(form_data: OAuth2PasswordRequestForm = Depends()): username = form_data.username password = form_data.password # Verify username and password here # Return access token if valid return {'access_token': 'token123', 'token_type': 'bearer'}
Use OAuth2PasswordRequestForm to get username and password from form data.
The endpoint usually returns a JSON with access_token and token_type.
from fastapi import FastAPI, Depends from fastapi.security import OAuth2PasswordRequestForm app = FastAPI() @app.post('/token') async def login(form_data: OAuth2PasswordRequestForm = Depends()): return {'access_token': form_data.username + '_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()): if form_data.username != 'user' or form_data.password != 'pass': raise HTTPException(status_code=400, detail='Incorrect username or password') return {'access_token': 'securetoken123', 'token_type': 'bearer'}
This FastAPI app has a /token endpoint that accepts username and password using OAuth2 password flow. It checks the username and password against a fake database. If correct, it returns an access token. If not, it returns an error.
from fastapi import FastAPI, Depends, HTTPException from fastapi.security import OAuth2PasswordRequestForm from fastapi.responses import JSONResponse app = FastAPI() fake_users_db = { 'alice': 'wonderland123', 'bob': 'builder456' } @app.post('/token') async def login(form_data: OAuth2PasswordRequestForm = Depends()): username = form_data.username password = form_data.password if username not in fake_users_db or fake_users_db[username] != password: raise HTTPException(status_code=400, detail='Incorrect username or password') token = f'{username}_token_abc123' return {'access_token': token, 'token_type': 'bearer'}
Never use OAuth2 password flow in apps you don't fully control because users share their passwords.
Always use HTTPS to protect username and password during transmission.
In real apps, verify passwords securely and generate real tokens (like JWT).
OAuth2 password flow lets users log in by sending username and password to your app.
FastAPI provides OAuth2PasswordRequestForm to handle this easily.
Use this flow only in trusted apps and always protect user data carefully.