0
0
MicroservicesHow-ToBeginner ยท 4 min read

How to Use JWT for Microservices Authentication

Use JWT (JSON Web Tokens) to securely pass user identity and permissions between microservices. Each microservice validates the JWT signature and claims to authenticate requests without central session storage.
๐Ÿ“

Syntax

A JWT consists of three parts separated by dots: header, payload, and signature. The header defines the token type and algorithm. The payload contains user data and claims. The signature ensures the token is not tampered with.

Example JWT format:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOiIxMjM0NSIsImF1ZCI6Im15bWljcm9zZXJ2aWNlcyIsImlhdCI6MTY4NjAwMDAwMCwiZXhwIjoxNjg2MDAzNjAwfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c

python
header = {"alg": "HS256", "typ": "JWT"}
payload = {"userId": "12345", "aud": "mymicroservices", "iat": 1686000000, "exp": 1686003600}
signature = HMACSHA256(base64UrlEncode(header) + "." + base64UrlEncode(payload), secret)
๐Ÿ’ป

Example

This example shows a simple flow where a user logs in, receives a JWT, and microservices verify the token to allow access.

python
import jwt
import time

# Secret key for signing tokens
SECRET_KEY = 'mysecretkey'

# Function to create JWT
def create_jwt(user_id):
    payload = {
        'userId': user_id,
        'iat': int(time.time()),
        'exp': int(time.time()) + 3600,  # expires in 1 hour
        'aud': 'microservices'
    }
    token = jwt.encode(payload, SECRET_KEY, algorithm='HS256')
    return token

# Function to verify JWT
def verify_jwt(token):
    try:
        decoded = jwt.decode(token, SECRET_KEY, algorithms=['HS256'], audience='microservices')
        return decoded
    except jwt.ExpiredSignatureError:
        return 'Token expired'
    except jwt.InvalidTokenError:
        return 'Invalid token'

# Simulate user login
user_token = create_jwt('user123')
print('JWT:', user_token)

# Simulate microservice verifying token
verification_result = verify_jwt(user_token)
print('Verification:', verification_result)
Output
JWT: <token_string> Verification: {'userId': 'user123', 'iat': 1686000000, 'exp': 1686003600, 'aud': 'microservices'}
โš ๏ธ

Common Pitfalls

  • Not validating the token signature: This allows attackers to forge tokens.
  • Ignoring token expiration: Leads to accepting old tokens and security risks.
  • Not checking audience or issuer claims: Can cause tokens meant for other services to be accepted.
  • Sharing secret keys insecurely: Compromises all tokens.
  • Storing sensitive data in payload: JWT payload is base64 encoded, not encrypted.
python
## Wrong: Not verifying signature
# decoded = jwt.decode(token, options={"verify_signature": False})

## Right: Always verify signature and claims
# decoded = jwt.decode(token, SECRET_KEY, algorithms=['HS256'], audience='microservices')
๐Ÿ“Š

Quick Reference

Remember these key points when using JWT for microservices authentication:

  • Sign tokens with a strong secret or private key.
  • Validate signature, expiration, audience, and issuer in every microservice.
  • Keep tokens short and avoid sensitive info in payload.
  • Use HTTPS to protect tokens in transit.
  • Refresh tokens periodically to limit risk.
โœ…

Key Takeaways

Use JWT to pass user identity securely between microservices without central session storage.
Always validate JWT signature, expiration, and claims in each microservice.
Keep JWT payload minimal and never store sensitive data inside it.
Protect JWTs in transit using HTTPS and manage secret keys securely.
Handle token expiration and refresh tokens to maintain security.