Category: python
Authentication vs Authorization in Microservices
Published on 22 Aug 2026
Explanation
Authentication verifies who the user or service is, while authorization determines what that authenticated identity is allowed to do. In a microservices architecture, authentication is commonly handled using tokens such as JWT. After a user successfully logs in, an authentication service can issue a token. The client sends that token when calling the API Gateway or individual services. Authorization rules then determine whether the user can perform operations such as viewing products, creating orders, or managing employees.
Code:
from fastapi import FastAPI, Header, HTTPException
app = FastAPI()
@app.get('/profile')
def get_profile(authorization: str | None = Header(default=None)):
if not authorization:
raise HTTPException(
status_code=401,
detail='Authentication required'
)
return {
'message': 'User is authenticated'
}
Explanation
JSON Web Token (JWT) is commonly used for authentication in stateless APIs. After successful login, the server creates a signed token containing information such as the user ID and expiration time. The client sends the token in the Authorization header using the Bearer scheme. The receiving service validates the token before allowing access to protected endpoints. JWT allows multiple microservices to validate the same token without maintaining a server-side session for every request.
Code:
# Install required packages
# pip install pyjwt
import jwt
from datetime import datetime, timedelta, timezone
SECRET_KEY = 'change-this-in-production'
payload = {
'user_id': 101,
'exp': datetime.now(timezone.utc) + timedelta(minutes=30)
}
token = jwt.encode(
payload,
SECRET_KEY,
algorithm='HS256'
)
print('JWT:', token)
# Decode and validate the token
try:
data = jwt.decode(
token,
SECRET_KEY,
algorithms=['HS256']
)
print('User ID:', data['user_id'])
except jwt.InvalidTokenError:
print('Invalid token')
Explanation
FastAPI provides security utilities such as HTTPBearer and OAuth2PasswordBearer for handling authentication tokens. A dependency can validate the token before the endpoint executes. This creates a reusable authentication mechanism that can be applied to multiple routes. In a production system, token validation should verify the signature, expiration time, issuer, audience, and other required claims according to the application's security design.
Code:
from fastapi import FastAPI, Depends, HTTPException
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
app = FastAPI()
security = HTTPBearer()
async def authenticate(
credentials: HTTPAuthorizationCredentials = Depends(security)
):
token = credentials.credentials
if token != 'valid-token':
raise HTTPException(
status_code=401,
detail='Invalid authentication token'
)
return {'user_id': 101}
@app.get('/profile')
async def profile(user=Depends(authenticate)):
return {
'message': 'Protected resource',
'user': user
}
Explanation
Authorization controls what an authenticated user is allowed to do. A common approach is Role-Based Access Control (RBAC), where users are assigned roles such as admin, manager, or user. Each role has specific permissions. For example, an admin may delete employees while a normal user can only view employee information. Authorization should be enforced on protected operations and should not rely only on frontend restrictions.
Code:
from fastapi import FastAPI, Depends, HTTPException
app = FastAPI()
current_user = {
'id': 101,
'name': 'John',
'role': 'admin'
}
def require_admin():
if current_user['role'] != 'admin':
raise HTTPException(
status_code=403,
detail='Admin access required'
)
return current_user
@app.delete('/employees/{employee_id}')
def delete_employee(
employee_id: int,
user=Depends(require_admin)
):
return {
'message': 'Employee deleted',
'employee_id': employee_id
}
Explanation
In a microservices system, an API Gateway can act as the first authentication layer by validating access tokens before routing requests to internal services. Individual services should still enforce authorization for their own business resources instead of blindly trusting the gateway. For service-to-service communication, services can use service credentials, mTLS, OAuth2 client credentials, or signed tokens depending on the security architecture. HTTPS should be used for communication, secrets should be stored securely, and tokens should have appropriate expiration and permissions.
Code:
# Microservices Security Flow # # Client # | # | Bearer JWT # v # API Gateway # | # Authenticate Token # | # +--------+--------+ # | | | # v v v # User Order Payment # Service Service Service # | | | # +--------+--------+ # | # Authorization # at each service # # Common security components: # - JWT / OAuth2 # - HTTPS # - API Gateway # - RBAC / Permissions # - Service-to-service authentication # - Secrets Management # - Token Expiration