Welcome to the final lesson of our course on securing your Python REST API. In this lesson, we will explore context-aware validation and advanced token lifecycle management using Pydantic models throughout. These techniques build on the database-backed token blacklisting you learned in Unit 3, adding additional layers of security through role-based access control and contextual checks. By the end of this lesson, you will understand how to combine these powerful security mechanisms with type-safe Pydantic models to create a robust, production-ready authentication system.
Production Deployment Considerations
Before we dive into context-aware validation, it's important to note that this course uses simplified configurations for educational purposes. In production environments, you need additional security hardening:
CORS Configuration:
The course examples use permissive CORS settings (allow_origins=["*"] with allow_credentials=True) for convenience. This configuration:
Will be rejected by modern browsers (they don't allow wildcard origins with credentials)
Is a major security risk if it did work (any site could make authenticated requests)
In production, always use explicit origin allowlists:
Understanding Context-Aware Validation with Pydantic
Context-aware validation goes beyond basic token verification by considering additional factors surrounding the token usage. While standard validation simply verifies that a token is valid and not expired, context-aware validation examines:
Who is using the token (user identity and role)
Where the token is being used from (IP address, device)
What the token is trying to access (resource permissions)
When the token is being used (time restrictions)
How the token is being presented (header format, encryption)
Pydantic's Role in Context-Aware Security:
Request validation ensures we receive properly formatted security context
Token Creation: Generating tokens with appropriate claims and contexts
Token Storage: Securely storing tokens on both client and server sides (database for refresh tokens)
Token Validation: Verifying tokens against multiple contextual factors
Token Renewal: Safely refreshing tokens without security compromises
Token Revocation: Invalidating tokens using the database-backed blacklist from Unit 3
In Unit 3, you learned how to implement database-backed token blacklisting using the TokenBlacklist model. This provides persistent, scalable token revocation that works across server restarts and in distributed systems. In this unit, we'll build on that foundation by adding role-based access control and IP validation with Pydantic validation throughout.
Role-Based Access Control (RBAC)
Role-Based Access Control (RBAC) is a method of restricting access to resources based on the roles of individual users. In our API, we use the role_required dependency function to enforce RBAC. Here's how it works:
from ..models.token_blacklist import TokenBlacklistfrom ..config import get_jwt_secretasync def check_token_blacklist(token: str, db: AsyncSession) -> bool: """Check if token is in the database blacklist (from Unit 3)""" result = await db.execute( select(TokenBlacklist).where(TokenBlacklist.token == token) ) return result.scalar_one_or_none() is not Nonedef role_required(required_role: Role): """ Dependency function that checks if a user has the required role Returns a dependency function that can be used with Depends() """ async def check_role(request: Request, db: AsyncSession = Depends(get_db)): authorization = request.headers.get('authorization', '') if not authorization: raise HTTPException(status_code=401, detail='Missing token') token = authorization.split(' ')[1] if authorization.startswith('Bearer ') else authorization # Check database blacklist (from Unit 3) if await check_token_blacklist(token, db): raise HTTPException(status_code=403, detail='Token revoked') try: decoded = jwt.decode(token, get_jwt_secret(), algorithms=['HS256']) if decoded.get('role') != required_role.value: raise HTTPException(status_code=403, detail='Insufficient privileges') # Get user from database to confirm role result = await db.execute(select(User).where(User.id == decoded['userId'])) user = result.scalar_one_or_none() if not user: raise HTTPException(status_code=401, detail='User not found') return user except jwt.JWTError: raise HTTPException(status_code=401, detail='Invalid or expired token') return check_role
The key logic here is that this dependency:
Checks the database blacklist using the check_token_blacklist function from Unit 3
Extracts the user's role from the JWT token using our secure get_jwt_secret() function
Compares it against the required role for the route
Retrieves the user from the database to confirm their current role
The function returns an async dependency that can be applied to any route using FastAPI's Depends(), with the required role passed as an argument. If the user's role doesn't match what's required, access is denied with a 403 status code.
IP Address Validation in Tokens
Including IP addresses in tokens adds an extra layer of security by ensuring that tokens are used only from expected locations:
request_ip = request.headers.get('x-forwarded-for') or request.client.hostif decoded.get('ip') and decoded['ip'] != request_ip: raise HTTPException(status_code=403, detail='Token used from unexpected IP')
The core idea is to bind a token to the IP address from which it was issued. The code extracts the current request's IP address and compares it to the IP stored in the token. This creates a context-aware validation that prevents token theft across different networks - even if a token is stolen, it can't be used from a different IP address.
For refresh tokens, this provides an additional security layer, as they're particularly valuable targets due to their longer lifespans.
Important Limitations of IP Validation
IP validation can lock out legitimate users:
Mobile users switching between WiFi and cellular
VPN users with rotating IPs
Users behind corporate NAT that changes IPs
Residential ISPs that rotate addresses
This strict approach often creates more problems than it solves for consumer applications.
Security warning about X-Forwarded-For:
The header X-Forwarded-For can be spoofed by attackers if your app isn't behind a trusted proxy (like nginx). An attacker could fake their IP address to bypass validation. Only trust this header if you've configured FastAPI to work with your specific proxy setup.
Recommended approach:
Skip IP validation for most consumer apps - user convenience matters
Use it optionally for high-security contexts (banking, admin panels)
Consider alternatives like checking user agent consistency or monitoring login patterns instead
IP binding is demonstrated here as an example of context-aware validation, but you should carefully evaluate whether it's appropriate for your specific use case.
Integrating Context-Aware Validation with Pydantic Models
When applying context-aware validation to refresh tokens, we create a multi-layered security system with type-safe Pydantic models:
from ..models.token_blacklist import TokenBlacklistfrom ..middleware.auth_middleware import revoke_access_token, check_token_blacklistfrom ..schemas.auth import RefreshRequest, TokenResponsefrom ..config import get_jwt_secretREFRESH_TOKEN_SECRET = get_jwt_secret() # Use the secure secret getter@router.post('/refresh', response_model=TokenResponse)async def refresh_token(request: RefreshRequest, req: Request, db: AsyncSession = Depends(get_db)): """REFRESH - Exchanges refresh token for a new access token (ROTATION)""" # request.refreshToken is already validated by Pydantic! refresh_token = request.refreshToken # Validate token existence if not refresh_token: raise HTTPException(status_code=400, detail='Refresh token required') # Check database blacklist (from Unit 3) if await check_token_blacklist(refresh_token, db): raise HTTPException(status_code=401, detail='Token has been revoked') try: # Verify token signature using secure secret getter decoded = jwt.decode(refresh_token, get_jwt_secret(), algorithms=['HS256']) # Context validation: check IP address request_ip = req.headers.get('x-forwarded-for') or req.client.host if decoded.get('ip') and decoded['ip'] != request_ip: # Add token to database blacklist (Unit 3 function) await revoke_access_token(refresh_token, db, 'IP mismatch detected') raise HTTPException(status_code=403, detail='Token used from unexpected IP') # Context validation: check user agent user_agent = req.headers.get('user-agent') if decoded.get('userAgent') and decoded['userAgent'] != user_agent: # Add token to database blacklist (Unit 3 function) await revoke_access_token(refresh_token, db, 'User agent mismatch detected') raise HTTPException(status_code=403, detail='Token used from unexpected client') # Generate new tokens if all validation passes new_access_token = generate_access_token(decoded['userId'], decoded['role']) return TokenResponse(accessToken=new_access_token, refreshToken="") except jwt.JWTError: raise HTTPException(status_code=401, detail='Invalid refresh token')
Benefits of Using Pydantic Here:
RefreshRequest ensures the token is present and properly formatted
TokenResponse guarantees the response structure
Type safety prevents runtime errors in security-critical code
API documentation shows exact security requirements
Testing Context-Aware Validation
To verify our detection system works, we'll simulate a token theft scenario:
def test_context_aware_validation(): # Login as normal user to get token response = requests.post('http://localhost:3000/api/auth/login', json={ 'username': 'contextUser', 'password': 'pass123' }) user_login_data = response.json() user_token = user_login_data.get('token') # Normal user tries admin route => expect 403 response = requests.get('http://localhost:3000/api/snippets/all', headers={ 'Authorization': f'Bearer {user_token}' }) print(f'Normal user status => {response.status_code}')
This test demonstrates a real-world scenario where a standard user attempts to access an admin-only endpoint. The main goal is to verify that our RBAC system correctly denies access with a 403 status code. Testing these scenarios is critical to ensure your security measures are working as intended.
Summary and Conclusion
In this lesson, you learned about context-aware validation and how it builds on the database-backed token blacklisting from Unit 3. We covered:
Role-based access control (RBAC) for resource permissions
IP address validation for location-based security
User agent validation for device consistency
Integration with database-backed blacklisting for persistent revocation
Pydantic models for type-safe security operations
The production requirements for scalable token management
Secure JWT secret management using the get_jwt_secret() function
Critical security practice: Always verify token signatures before trusting claims to prevent DoS attacks
These approaches significantly enhance your API's defense against token abuse and unauthorized access by combining multiple security layers with persistent, auditable token revocation and type-safe Pydantic validation.
Congratulations on reaching the end of the course! You now have a comprehensive understanding of how to secure a Python REST API with FastAPI, from basic authentication to advanced context-aware validation with database-backed token management and Pydantic models throughout. As you move on to the practice exercises, remember to apply these concepts to reinforce your learning. Well done on completing this journey, and best of luck in your future endeavors!
from pydantic import BaseModel, Fieldfrom typing import Optionalclass RefreshWithContextRequest(BaseModel): """Request model with IP validation context""" refreshToken: str = Field(alias='refreshToken') expectedIp: Optional[str] = None # For testing IP validation class Config: populate_by_name = Trueclass SecurityContextResponse(BaseModel): """Response showing detected security context""" success: bool userId: int ipAddress: str userAgent: str
Python
from ..models.token_blacklist import TokenBlacklistfrom ..config import get_jwt_secretasync def check_token_blacklist(token: str, db: AsyncSession) -> bool: """Check if token is in the database blacklist (from Unit 3)""" result = await db.execute( select(TokenBlacklist).where(TokenBlacklist.token == token) ) return result.scalar_one_or_none() is not Nonedef role_required(required_role: Role): """ Dependency function that checks if a user has the required role Returns a dependency function that can be used with Depends() """ async def check_role(request: Request, db: AsyncSession = Depends(get_db)): authorization = request.headers.get('authorization', '') if not authorization: raise HTTPException(status_code=401, detail='Missing token') token = authorization.split(' ')[1] if authorization.startswith('Bearer ') else authorization # Check database blacklist (from Unit 3) if await check_token_blacklist(token, db): raise HTTPException(status_code=403, detail='Token revoked') try: decoded = jwt.decode(token, get_jwt_secret(), algorithms=['HS256']) if decoded.get('role') != required_role.value: raise HTTPException(status_code=403, detail='Insufficient privileges') # Get user from database to confirm role result = await db.execute(select(User).where(User.id == decoded['userId'])) user = result.scalar_one_or_none() if not user: raise HTTPException(status_code=401, detail='User not found') return user except jwt.JWTError: raise HTTPException(status_code=401, detail='Invalid or expired token') return check_role
Python
request_ip = request.headers.get('x-forwarded-for') or request.client.hostif decoded.get('ip') and decoded['ip'] != request_ip: raise HTTPException(status_code=403, detail='Token used from unexpected IP')
Python
from ..models.token_blacklist import TokenBlacklistfrom ..middleware.auth_middleware import revoke_access_token, check_token_blacklistfrom ..schemas.auth import RefreshRequest, TokenResponsefrom ..config import get_jwt_secretREFRESH_TOKEN_SECRET = get_jwt_secret() # Use the secure secret getter@router.post('/refresh', response_model=TokenResponse)async def refresh_token(request: RefreshRequest, req: Request, db: AsyncSession = Depends(get_db)): """REFRESH - Exchanges refresh token for a new access token (ROTATION)""" # request.refreshToken is already validated by Pydantic! refresh_token = request.refreshToken # Validate token existence if not refresh_token: raise HTTPException(status_code=400, detail='Refresh token required') # Check database blacklist (from Unit 3) if await check_token_blacklist(refresh_token, db): raise HTTPException(status_code=401, detail='Token has been revoked') try: # Verify token signature using secure secret getter decoded = jwt.decode(refresh_token, get_jwt_secret(), algorithms=['HS256']) # Context validation: check IP address request_ip = req.headers.get('x-forwarded-for') or req.client.host if decoded.get('ip') and decoded['ip'] != request_ip: # Add token to database blacklist (Unit 3 function) await revoke_access_token(refresh_token, db, 'IP mismatch detected') raise HTTPException(status_code=403, detail='Token used from unexpected IP') # Context validation: check user agent user_agent = req.headers.get('user-agent') if decoded.get('userAgent') and decoded['userAgent'] != user_agent: # Add token to database blacklist (Unit 3 function) await revoke_access_token(refresh_token, db, 'User agent mismatch detected') raise HTTPException(status_code=403, detail='Token used from unexpected client') # Generate new tokens if all validation passes new_access_token = generate_access_token(decoded['userId'], decoded['role']) return TokenResponse(accessToken=new_access_token, refreshToken="") except jwt.JWTError: raise HTTPException(status_code=401, detail='Invalid refresh token')
Python
def test_context_aware_validation(): # Login as normal user to get token response = requests.post('http://localhost:3000/api/auth/login', json={ 'username': 'contextUser', 'password': 'pass123' }) user_login_data = response.json() user_token = user_login_data.get('token') # Normal user tries admin route => expect 403 response = requests.get('http://localhost:3000/api/snippets/all', headers={ 'Authorization': f'Bearer {user_token}' }) print(f'Normal user status => {response.status_code}')