
FastAPI
Learn essential concepts of oauth2 in FastAPI.
This section covers the fundamentals of OAuth2, including:
OAuth2 is a standard authorization protocol that allows users to grant third-party applications access to their resources without sharing passwords.
OAuth2 supports multiple flows:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from datetime import datetime, timedelta
from jose import JWTError, jwt
from pydantic import BaseModel
app = FastAPI()
SECRET_KEY = "your-secret-key"
ALGORITHM = "HS256"
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")
class User(BaseModel):
username: str
email: str = None
full_name: str = None
disabled: bool = None
class UserInDB(User):
hashed_password: str
# Fake database
fake_users_db = {
"johndoe": {
"username": "johndoe",
"full_name": "John Doe",
"email": "john@example.com",
"hashed_password": "fakehashed1234567890",
"disabled": False,
}
}
async def get_current_user(token: str = Depends(oauth2_scheme)):
try:
payload = jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
username: str = payload.get("sub")
if username is None:
raise HTTPException(status_code=401, detail="Invalid token")
except JWTError:
raise HTTPException(status_code=401, detail="Invalid token")
user = fake_users_db.get(username)
if user is None:
raise HTTPException(status_code=401, detail="User not found")
return user
@app.post("/token")
async def login(form_data: OAuth2PasswordRequestForm = Depends()):
user = fake_users_db.get(form_data.username)
if not user:
raise HTTPException(status_code=401, detail="Invalid credentials")
access_token_expires = timedelta(hours=1)
expire = datetime.utcnow() + access_token_expires
to_encode = {"sub": user["username"], "exp": expire}
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return {"access_token": encoded_jwt, "token_type": "bearer"}
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_userOAuth2 is essential for:
Next step: Explore the advanced section for production patterns and optimization techniques.
Resources
Ojasa Mirai
Master AI-powered development skills through structured learning, real projects, and verified credentials. Whether you're upskilling your team or launching your career, we deliver the skills companies actually need.
Learn Deep • Build Real • Verify Skills • Launch Forward