Authentication & Security¶
Learn how to implement secure authentication in your FastAPI application. The boilerplate provides a complete JWT-based authentication system with user management, permissions, and security best practices.
What You'll Learn¶
- JWT Tokens - Understand access and refresh token management
- User Management - Handle registration, login, and user profiles
- Permissions - Implement role-based access control and authorization
Authentication Overview¶
The system uses JWT tokens with refresh token rotation for secure, stateless authentication:
# Basic login flow@router.post("/login",response_model=Token)asyncdeflogin_for_access_token(response:Response,form_data:OAuth2PasswordRequestForm):user=awaitauthenticate_user(form_data.username,form_data.password,db)access_token=awaitcreate_access_token(data={"sub":user["username"]})refresh_token=awaitcreate_refresh_token(data={"sub":user["username"]})# Set secure HTTP-only cookie for refresh tokenresponse.set_cookie("refresh_token",refresh_token,httponly=True,secure=True)return{"access_token":access_token,"token_type":"bearer"}Key Features¶
JWT Token System¶
- Access tokens: Short-lived (30 minutes), for API requests
- Refresh tokens: Long-lived (7 days), stored in secure cookies
- Token blacklisting: Secure logout implementation
- Automatic expiration: Built-in token lifecycle management
User Management¶
- Flexible authentication: Username or email login
- Secure passwords: bcrypt hashing with salt
- Profile management: Complete user CRUD operations
- Soft delete: User deactivation without data loss
Permission System¶
- Superuser privileges: Administrative access control
- Resource ownership: User-specific data access
- User tiers: Subscription-based feature access
- Rate limiting: Per-user and per-tier API limits
Authentication Patterns¶
Endpoint Protection¶
# Required authentication@router.get("/protected")asyncdefprotected_endpoint(current_user:dict=Depends(get_current_user)):return{"message":f"Hello{current_user['username']}"}# Optional authentication@router.get("/public")asyncdefpublic_endpoint(user:dict|None=Depends(get_optional_user)):ifuser:return{"premium_content":True}return{"premium_content":False}# Superuser only@router.get("/admin",dependencies=[Depends(get_current_superuser)])asyncdefadmin_endpoint():return{"admin_data":"sensitive"}Resource Ownership¶
@router.patch("/posts/{post_id}")asyncdefupdate_post(post_id:int,current_user:dict=Depends(get_current_user)):post=awaitcrud_posts.get(db=db,id=post_id)# Check ownership or admin privilegesifpost["created_by_user_id"]!=current_user["id"]andnotcurrent_user["is_superuser"]:raiseForbiddenException("Cannot update other users' posts")returnawaitcrud_posts.update(db=db,id=post_id,object=updates)Security Features¶
Token Security¶
- Short-lived access tokens limit exposure
- HTTP-only refresh token cookies prevent XSS
- Token blacklisting enables secure logout
- Configurable token expiration times
Password Security¶
- bcrypt hashing with automatic salt generation
- Configurable password complexity requirements
- No plain text passwords stored anywhere
- Rate limiting on authentication endpoints
API Protection¶
- CORS policies for cross-origin request control
- Rate limiting prevents brute force attacks
- Input validation prevents injection attacks
- Consistent error messages prevent information disclosure
Configuration¶
JWT Settings¶
SECRET_KEY="your-super-secret-key-here"ALGORITHM="HS256"ACCESS_TOKEN_EXPIRE_MINUTES=30REFRESH_TOKEN_EXPIRE_DAYS=7Security Settings¶
# Cookie securityCOOKIE_SECURE=trueCOOKIE_SAMESITE="lax"# Password requirementsPASSWORD_MIN_LENGTH=8ENABLE_PASSWORD_COMPLEXITY=trueGetting Started¶
Follow this progressive learning path:
1.JWT Tokens - Foundation¶
Understand how JWT tokens work, including access and refresh token management, verification, and blacklisting.
2.User Management - Core Features¶
Implement user registration, login, profile management, and administrative operations.
3.Permissions - Access Control¶
Set up role-based access control, resource ownership checking, and tier-based permissions.
Implementation Examples¶
Quick Authentication Setup¶
# Protect an endpoint@router.get("/my-data")asyncdefget_my_data(current_user:dict=Depends(get_current_user)):returnawaitget_user_specific_data(current_user["id"])# Check user permissionsdefcheck_tier_access(user:dict,required_tier:str):ifnotuser.get("tier")oruser["tier"]["name"]!=required_tier:raiseForbiddenException(f"Requires{required_tier} tier")# Custom authentication dependencyasyncdefget_premium_user(current_user:dict=Depends(get_current_user)):check_tier_access(current_user,"Pro")returncurrent_userFrontend Integration¶
// Basic authentication flowclassAuthManager{asynclogin(username,password){constresponse=awaitfetch('/api/v1/login',{method:'POST',headers:{'Content-Type':'application/x-www-form-urlencoded'},body:newURLSearchParams({username,password})});consttokens=awaitresponse.json();localStorage.setItem('access_token',tokens.access_token);returntokens;}asyncmakeAuthenticatedRequest(url,options={}){consttoken=localStorage.getItem('access_token');returnfetch(url,{...options,headers:{...options.headers,'Authorization':`Bearer${token}`}});}}What's Next¶
Start building your authentication system:
- JWT Tokens - Learn token creation, verification, and lifecycle management
- User Management - Implement registration, login, and profile operations
- Permissions - Add authorization patterns and access control
The authentication system provides a secure foundation for your API. Each guide includes practical examples and implementation details for production-ready authentication.