The before code shows Service A calling Service B without forwarding the JWT token, so Service B cannot authenticate the user. The after code extracts the JWT token from the incoming request headers in Service A and forwards it to Service B. Service B then validates the token locally before processing the request, enabling secure token propagation.
### Before: No token propagation, downstream service cannot authenticate
# Service A handler
def service_a_handler(request):
# Process request without forwarding token
response = call_service_b(request.data)
return response
### After: Propagate JWT token in headers
# Service A handler
def service_a_handler(request):
jwt_token = request.headers.get('Authorization')
headers = {'Authorization': jwt_token} if jwt_token else {}
response = call_service_b(request.data, headers=headers)
return response
# Service B handler
def service_b_handler(request):
jwt_token = request.headers.get('Authorization')
if not validate_jwt(jwt_token):
return {'error': 'Unauthorized'}, 401
# Proceed with authorized request
return {'data': 'success'}
# Helper function
def validate_jwt(token):
# Simplified validation logic
if token and token.startswith('Bearer '):
# Decode and verify signature, expiry, etc.
return True
return False