How does Authentication & Authorization work in Microservices (JWT & OAuth2)?

Authentication vs Authorization

  • Authentication β†’ Who are you? (identity)

  • Authorization β†’ What can you access? (permissions)


πŸ”Ή Challenge in Microservices

How does Authentication & Authorization work in Microservices (JWT & OAuth2)?

  • Multiple services

  • Stateless REST APIs

  • Shared security logic

  • Avoid session replication

πŸ‘‰ Solution: Token-based security (JWT + OAuth2)


πŸ”Ή OAuth2 (High-Level)

OAuth2 is a delegation framework:

  • User authenticates once

  • Gets an access token

  • Token is used to access services

πŸ“Œ Components:

  • Authorization Server

  • Resource Server (Microservices)

  • Client (UI / App)


πŸ”Ή JWT (JSON Web Token)

JWT is a self-contained token that includes:

  • User info

  • Roles

  • Expiry

  • Signature

πŸ“Œ Structure:

Header.Payload.Signature

πŸ”Ή Authentication Flow (Step-by-Step)

  1. User logs in

  2. Auth Server validates credentials

  3. Auth Server generates JWT

  4. Client sends JWT in Authorization header

  5. API Gateway validates token

  6. Request forwarded to microservice

  7. Microservice authorizes based on roles


πŸ”Ή Where Security Logic Lives?

Component Responsibility
API Gateway Token validation, rate limiting
Auth Server Login, token issuing
Microservices Role-based access

πŸ”Ή Spring Security Example

http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
)
.oauth2ResourceServer()
.jwt();

πŸ”Ή Advantages

βœ… Stateless
βœ… Scalable
βœ… No session storage
βœ… Works well with microservices


πŸ”Ή Challenges

❌ Token revocation is hard
❌ Token expiry handling
❌ Key rotation


πŸ”Ή Best Practices

  • Short-lived access tokens

  • Refresh tokens

  • Validate JWT at API Gateway

  • Use HTTPS always


⭐ Interview One-Liner

β€œMicroservices typically use OAuth2 with JWT for stateless, scalable authentication and role-based authorization.”


πŸ”Ή Follow-Up Questions

  • JWT vs Session?

  • How do you revoke JWT?

  • Where do you store refresh tokens?

Leave a Reply