Question 23 Β· Section 17

How to implement authentication and authorization in microservices

Structured Java interview answer with junior, middle, and senior-level explanation.

Language versions: English Russian Ukrainian

🟒 Junior Level

Authentication β€” who are you? (identity verification)

Authorization β€” what are you allowed to do? (permission check)

The most popular approach β€” JWT tokens:

1. Client β†’ Login Service β†’ username/password
2. Login Service β†’ JWT token
3. Client β†’ JWT token β†’ API Gateway β†’ token validation
4. API Gateway β†’ forwards to services + userId in header

JWT token contains:

  • Who the user is (userId, roles)
  • Signature (to prevent forgery)

🟑 Middle Level

JWT in API Gateway

@Component
public class AuthFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain chain) {
        String token = request.getHeader("Authorization");

        if (token != null && token.startsWith("Bearer ")) {
            try {
                // JwtUtil β€” example utility class. In production, use Spring Security JWT
                // or a library like java-jwt (Auth0) / nimbus-jose-jwt.
                Claims claims = JwtUtil.parseToken(token.substring(7));
                request.setAttribute("userId", claims.get("userId"));
                request.setAttribute("roles", claims.get("roles"));
            } catch (JwtException e) {
                response.setStatus(HttpStatus.UNAUTHORIZED.value());
                return;
            }
        }

        chain.doFilter(request, response);
    }
}

OAuth 2.0 / OpenID Connect

Client β†’ Auth Server (Keycloak) β†’ Authorization Code
Client β†’ Auth Server β†’ Access Token + ID Token
Client β†’ API Gateway + Access Token β†’ Service

Common mistakes

  1. Token validation in every service:
    Every service validates the token β†’ cryptographic overhead (JWT signing is RSA/ECDSA).
    At 10K req/s across 20 services = 200K HMAC/RSA operations. Solution: API Gateway
    validates once and passes the result via header.
    

When NOT to use JWT

  • High revocation requirements β€” JWT is hard to revoke (needs a blacklist)
  • Session-based is better when instant session termination is needed
  • OAuth2 Device Flow for devices without a browser

πŸ”΄ Senior Level

Token propagation

Gateway β†’ Service A β†’ Service B
         Access Token is passed along the chain

mTLS (mutual TLS)

Service A ↔ Service B: mutual certificate verification
Additional protection for service-to-service communication

Production Experience

Keycloak + Spring Security:

spring:
  security:
    oauth2:
      resourceserver:
        jwt:
          issuer-uri: http://keycloak:8080/realms/myrealm
          jwk-set-uri: http://keycloak:8080/realms/myrealm/protocol/openid-connect/certs

Best Practices

βœ… Token validation in Gateway
βœ… HTTPS always
βœ… Short-lived access tokens
βœ… Refresh tokens
βœ… mTLS for service-to-service
βœ… Rotate signing keys

❌ Storing secrets in the token
❌ Without expiration
❌ Validation in every service
❌ HTTP for tokens

🎯 Interview Cheat Sheet

Must know:

  • Authentication = who are you, authorization = what are you allowed to do
  • JWT token: userId + roles + signature, passed in Authorization: Bearer header
  • API Gateway validates the token once β€” services receive the result via header (avoids crypto overhead)
  • OAuth 2.0 / OpenID Connect β€” standard approach with Auth Server (Keycloak)
  • mTLS for service-to-service β€” mutual certificate verification
  • Short-lived access tokens + refresh tokens β€” security balance
  • Do NOT use JWT when high revocation requirements exist (need a blacklist)

Frequent follow-up questions:

  • Why not validate in every service? RSA/ECDSA signature is expensive. At 10K req/s across 20 services = 200K HMAC operations.
  • How to revoke a JWT? JWT is hard to revoke β€” need a blacklist or short-lived tokens. For instant revocation β€” session-based is better.
  • JWT vs OAuth2? JWT is a token format, OAuth2 is a protocol. OAuth2 can use JWT as an access token.
  • What is mTLS? Mutual TLS β€” both services verify each other’s certificates β€” service-to-service protection.

Red flags (NOT to say):

  • β€œEvery service validates JWT” β€” no, crypto overhead, Gateway validates once
  • β€œJWT can store secrets” β€” no, JWT is signed but NOT encrypted (payload is readable)
  • β€œAccess token without expiration” β€” no, if leaked, the attacker has permanent access
  • β€œHTTP for internal services” β€” no, tokens always over HTTPS

Related topics:

  • [[9. What is API Gateway and what problems does it solve]]
  • [[15. How to organize communication between microservices]]
  • [[7. What is Service Discovery and why is it needed]]
  • [[26. What tools are used for microservices orchestration]]
  • [[22. What is distributed tracing]]