Skip to main content

Implementing Request Authentication

1. Configuring JWT Authentication

Property Value Description
jwt.issuer "https://auth.example.com" Issuer URL for JWT tokens
jwt.audience "api-service" Expected audience for JWT tokens
jwt.publicKey "-----BEGIN PUBLIC KEY-----\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...\n-----END PUBLIC KEY-----" Public key for JWT signature verification
jwt.claimMapping {"sub": "user.id", "email": "user.email"} Mapping of JWT claims to service attributes

Example: JWT Authentication Configuration

jwt:
  issuer: https://auth.example.com
  audience: api-service
  publicKey: |
    -----BEGIN PUBLIC KEY-----
    MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA...
    -----END PUBLIC KEY-----
  claimMapping:
    sub: user.id
    email: user.email
Note: Ensure the public key matches the one used to sign JWTs by your identity provider.

2. Setting JWKS Endpoint

Property Value Description
jwks.endpoint https://auth.example.com/.well-known/jwks.json URL to the JSON Web Key Set (JWKS) endpoint used for validating JWT tokens
jwks.cacheTTL 300s Time-to-live for caching JWKS keys in seconds
jwks.retryAttempts 3 Number of retry attempts if JWKS endpoint is unreachable

Example: Configuring JWKS Endpoint in Service Mesh

auth:
  jwks:
    endpoint: https://auth.example.com/.well-known/jwks.json
    cacheTTL: 300s
    retryAttempts: 3
Note: Ensure the JWKS endpoint is accessible from all mesh nodes and supports CORS if accessed from browsers.

3. Configuring JWT Issuer and Audience

Property Value Description
jwt.issuer https://auth.example.com URL of the JWT issuer (Identity Provider)
jwt.audience api-service Expected audience claim in the JWT token

Example: JWT Configuration in Service Mesh

jwt:
  issuer: https://auth.example.com
  audience: api-service
Note: The issuer must match the iss claim in the JWT token, and audience must match the aud claim.

4. Implementing Request Authentication Selectors

Selector Type Description Example Notes
source.labels Matches requests based on source labels "source.labels": {"app": "frontend"} Used to authenticate requests from specific services
destination.labels Matches requests based on destination labels "destination.labels": {"app": "backend"} Used to enforce authentication for specific services
request.headers Matches requests based on header values "request.headers": {"Authorization": "Bearer.*"} Enforces authentication via headers
request.path Matches requests based on path patterns "request.path": "/api/v1/users" Can be used to apply auth to specific endpoints
request.method Matches requests based on HTTP method "request.method": "POST" Useful for applying auth to specific operations

Example: Authentication Selector Configuration

apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: jwt-auth
spec:
  selector:
    matchLabels:
      app: frontend
  jwt:
    - issuer: "https://issuer.example.com"
      jwksUri: "https://issuer.example.com/keys"

Example: Path-based Authentication

apiVersion: security.istio.io/v1beta1
kind: RequestAuthentication
metadata:
  name: api-auth
spec:
  selector:
    matchLabels:
      app: backend
  jwt:
    - issuer: "https://issuer.example.com"
      jwksUri: "https://issuer.example.com/keys"
  rules:
    - to:
        - operation:
            paths: ["/api/v1/users"]

5. Configuring JWT Claims Mapping

Property Description Default Value Notes
jwt.claims.mapping Maps JWT claims to custom headers or attributes None Used for transforming identity information in requests
jwt.claims.mapping.source Source claim in the JWT token None Can be any valid JWT claim like sub, email
jwt.claims.mapping.target Target header or attribute name in the service request None Example: X-User-ID

Example: JWT Claims Mapping Configuration

jwt:
  claims:
    mapping:
      - source: sub
        target: X-User-ID
      - source: email
        target: X-User-Email
Note: Ensure that the target headers are not reserved or used by the service itself to avoid conflicts.

6. Setting JWT Cache TTL

Property Value Description
jwt.cache.ttl 3600 Time-to-live for JWT cache in seconds
jwt.cache.refresh 300 Refresh interval for cached JWTs in seconds

Example: Configuring JWT Cache TTL

jwt:
  cache:
    ttl: 3600
    refresh: 300
Note: Setting a shorter TTL increases security by reducing the window of validity for cached tokens, but may increase latency due to more frequent token validation.

7. Implementing Output Payload Headers

Header Name Description Example Value Notes
Authorization Contains credentials for authenticating the client to the server Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9... Used in conjunction with JWT tokens for API access
X-Request-ID Unique identifier for tracking requests across services req-1234567890abcdef Helps in debugging and monitoring distributed systems
Content-Type Indicates the media type of the resource being sent in the request body application/json Essential for proper parsing and handling of payloads
X-Forwarded-For Identifies the original IP address of a client connecting to a web server through an HTTP proxy or load balancer 192.168.1.100 Used for logging and security purposes
X-Forwarded-Proto Indicates the protocol (HTTP or HTTPS) used to make the request https Helps in maintaining secure communication context

Example: Setting Output Headers in a Service Mesh

apiVersion: networking.istio.io/v1beta1
kind: VirtualService
metadata:
  name: example-service
spec:
  hosts:
  - example-service
  http:
  - route:
    - destination:
        host: example-service
    headers:
      response:
        add:
          X-Request-ID: "{{request.headers[X-Request-ID]}}"
          Authorization: "Bearer {{request.headers[Authorization]}}"
Note: When setting headers in a service mesh, ensure that they are properly sanitized to prevent header injection attacks.

8. Configuring Forward Original Token

Option Values Description
forward_original_token true | false Controls whether the original authentication token is forwarded to downstream services. Defaults to false.

Example: Forward Original Token Configuration

auth:
  forward_original_token: true
Note: Enabling this option allows downstream services to access the original token for further validation or use in their own authentication logic.

9. Managing Multiple JWT Issuers

Issuer Configuration Notes
issuer-1 {"jwksUri": "https://keycloak.example.com/realms/myrealm/protocol/openid-connect/certs", "audience": "api-service"} Primary issuer for internal services
issuer-2 {"jwksUri": "https://auth0.example.com/.well-known/jwks.json", "audience": "external-api"} External API authentication

Example: Configuring Multiple JWT Issuers in Istio

apiVersion: security.istio.io/v1
kind: RequestAuthentication
metadata:
  name: jwt-auth
spec:
  jwtRules:
  - issuer: https://keycloak.example.com/realms/myrealm
    jwksUri: https://keycloak.example.com/realms/myrealm/protocol/openid-connect/certs
    audiences:
    - api-service
  - issuer: https://auth0.example.com
    jwksUri: https://auth0.example.com/.well-known/jwks.json
    audiences:
    - external-api
Note: Ensure that each issuer's jwksUri is accessible to the service mesh for token validation.
Warning: Misconfiguring audience validation can lead to unauthorized access if tokens are accepted for the wrong service.

10. Troubleshooting JWT Authentication

Issue Possible Cause Solution
Token expired exp claim is in the past Refresh token or re-authenticate
Invalid signature Token signed with wrong key or algorithm Verify signing key and algorithm match
Audience mismatch aud claim doesn't match expected audience Ensure token was issued for correct service
Issuer mismatch iss claim doesn't match expected issuer Validate token source matches configured issuer
Missing required claims Essential claims like sub or exp missing Add required claims to JWT payload
Clock skew System time differs from token issuer time Adjust clock synchronization or allow skew tolerance

Example: Debugging Token Claims

// Example JWT decoding and validation
const jwt = require('jsonwebtoken');

try {
  const decoded = jwt.verify(token, publicKey);
  console.log('Decoded claims:', decoded);
} catch (err) {
  console.error('JWT verification failed:', err.message);
}
Note: Use tools like jwt.io to decode and inspect JWTs for debugging purposes.
Warning: Never log raw JWTs in production as they may contain sensitive information.

11. Implementing JWT Refresh Handling

Property Description Default Value Notes
jwt.refresh.enabled Enables or disables JWT refresh token handling false Set to true to enable refresh token support
jwt.refresh.expiry Expiry time for refresh tokens in seconds 3600 Refresh tokens expire after this duration
jwt.refresh.rotation Whether to rotate refresh tokens on use false When enabled, new refresh tokens are issued on use

Example: Configuring JWT Refresh Token

jwt:
  refresh:
    enabled: true
    expiry: 7200
    rotation: true
Note: Refresh tokens must be stored securely, typically in HTTP-only cookies to prevent XSS attacks.
Warning: If jwt.refresh.rotation is enabled, ensure that the client can handle token rotation without breaking session state.
Refresh Token Flow Description Status
1. Token Expiry Access token expires, client requests refresh Supported
2. Refresh Token Validation Service validates refresh token against store Supported
3. Token Rotation New access and refresh tokens issued Modern

12. Configuring JWT Validation Rules

Rule Description Configuration Notes
issuer URL of the JWT issuer "https://auth.example.com" Must match the iss claim in the JWT
audience Expected audience for the token "api-service" Must match the aud claim in the JWT
requiredClaims List of required claims in the JWT ["iss", "aud", "exp"] Claims must be present in the token
clockTolerance Allowed clock skew in seconds for token expiration 30 Default is 30 seconds to account for time drift
jwksUri URI to fetch JSON Web Key Set (JWKS) "https://auth.example.com/.well-known/jwks.json" Used to validate the token signature
allowedAlgorithms Allowed signing algorithms for JWTs ["RS256", "HS256"] Must match the alg header in the JWT

Example: JWT Validation Configuration

jwt:
  issuer: https://auth.example.com
  audience: api-service
  requiredClaims:
    - iss
    - aud
    - exp
  clockTolerance: 30
  jwksUri: https://auth.example.com/.well-known/jwks.json
  allowedAlgorithms:
    - RS256
    - HS256
Note: Ensure that the jwksUri is accessible to the service mesh and that the JWKS endpoint returns valid JSON Web Key Sets for signature verification.

Was this article helpful?