Definition
- OAuth 2.0 is an authorization framework that defines how applications can obtain limited access to user resources through tokens, without the application ever seeing the user's password.
- JWT (JSON Web Token) is a compact, self-contained token format with three Base64-encoded parts (header, payload, signature) that carries user claims and can be verified without a database lookup.
- RS256 is an asymmetric signing algorithm using RSA keys where the authorization server signs tokens with a private key and resource servers verify with the corresponding public key.
- Resource server is any microservice that holds protected data and validates the JWT before serving the request, configured in Spring Boot with ".oauth2ResourceServer(oauth2 -> oauth2.jwt())".
- Refresh token is a long-lived token used only to obtain new access tokens when the current one expires, stored securely and revocable in the database.
Think of National Bank of India issuing employee ID cards. The security office (authorization server) verifies Rajesh's identity and issues an ID card with his photo, name, department, and access level printed on it. The card has a holographic seal (RS256 signature) that only the security office's special printer can create. When Rajesh enters the vault area, the guard (resource server) checks the holographic seal (verifies signature), confirms the card has not expired, and checks that Rajesh's access level includes vault access. The guard does not need to call the security office each time: the card itself is proof.
Understanding the Concepts
What is OAuth 2.0?
OAuth 2.0 is an authorization framework that allows a third-party application to access a user's resources without knowing the user's password. The user authenticates with an authorization server (like Keycloak or Spring Authorization Server), which issues a token. The third-party application uses this token to access protected resources on behalf of the user.
In microservices, OAuth 2.0 solves the problem of how Service A knows that a request is legitimate and authorized. Instead of each service managing its own passwords, a central authorization server issues tokens. Every service validates the token before processing the request.
package com.bank.security;
public class OAuth2Concepts {
sealed interface OAuth2Role permits ResourceOwner, Client, AuthorizationServer, ResourceServer {}
record ResourceOwner(String name, String description) implements OAuth2Role {}
record Client(String name, String description) implements OAuth2Role {}
record AuthorizationServer(String name, String description) implements OAuth2Role {}
record ResourceServer(String name, String description) implements OAuth2Role {}
public static void main(String[] args) {
var roles = java.util.List.of(
new ResourceOwner("Rajesh (customer)", "The user who owns the bank account data"),
new Client("Mobile Banking App", "The application requesting access on behalf of Rajesh"),
new AuthorizationServer("auth-service", "Issues JWT tokens after verifying credentials"),
new ResourceServer("account-service", "Holds the protected data, validates tokens before serving requests")
);
System.out.println("OAuth 2.0 Roles in National Bank of India:");
for (var role : roles) {
String label = switch (role) {
case ResourceOwner r -> "Resource Owner: " + r.name() + " - " + r.description();
case Client c -> "Client: " + c.name() + " - " + c.description();
case AuthorizationServer a -> "Authorization Server:" + a.name() + " - " + a.description();
case ResourceServer rs -> "Resource Server: " + rs.name() + " - " + rs.description();
};
System.out.println(" " + label);
}
}
}
Expected output:
OAuth 2.0 Roles in National Bank of India:
Resource Owner: Rajesh (customer) - The user who owns the bank account data
Client: Mobile Banking App - The application requesting access on behalf of Rajesh
Authorization Server:auth-service - Issues JWT tokens after verifying credentials
Resource Server: account-service - Holds the protected data, validates tokens before serving requests
What is a JWT and what does it contain?
A JSON Web Token (JWT) is a compact, URL-safe token format that carries claims (information) about the user. A JWT has three parts separated by dots: header, payload, and signature.
The header contains the signing algorithm (RS256, HS256). The payload contains claims like user ID, roles, issued-at time, and expiration time. The signature is a cryptographic hash of the header and payload, signed with the server's private key (RS256) or a shared secret (HS256).
The key property of a JWT is that any service can verify it without calling the authorization server. The resource server uses the authorization server's public key to verify the signature. If the signature is valid and the token is not expired, the request is authenticated.
package com.bank.security;
import java.util.Base64;
public class JwtStructureDemo {
record JwtParts(String header, String payload, String signature) {}
public static void main(String[] args) {
// Simulated JWT (not real cryptography, for demonstration only)
var header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
var payload = "{\"sub\":\"rajesh-001\",\"name\":\"Rajesh Kumar\","
+ "\"roles\":[\"ROLE_CUSTOMER\",\"ROLE_TRANSFER\"],"
+ "\"iat\":1719849600,\"exp\":1719853200,"
+ "\"iss\":\"https://auth.nationalbankofindia.com\"}";
var signature = "RS256-SIGNATURE-BYTES";
var encodedHeader = Base64.getUrlEncoder().withoutPadding()
.encodeToString(header.getBytes());
var encodedPayload = Base64.getUrlEncoder().withoutPadding()
.encodeToString(payload.getBytes());
var encodedSignature = Base64.getUrlEncoder().withoutPadding()
.encodeToString(signature.getBytes());
System.out.println("JWT Structure:");
System.out.println(" Header (Base64): " + encodedHeader);
System.out.println(" Payload (Base64): " + encodedPayload.substring(0, 40) + "...");
System.out.println(" Signature: " + encodedSignature);
System.out.println();
System.out.println("Decoded Header: " + header);
System.out.println("Decoded Payload: " + payload);
System.out.println();
System.out.println("Key claims:");
System.out.println(" sub (subject): rajesh-001 (unique user ID)");
System.out.println(" roles: ROLE_CUSTOMER, ROLE_TRANSFER");
System.out.println(" iat (issued at): 1719849600 (Unix timestamp)");
System.out.println(" exp (expires): 1719853200 (1 hour later)");
System.out.println(" iss (issuer): https://auth.nationalbankofindia.com");
}
}
Expected output:
JWT Structure:
Header (Base64): eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9
Payload (Base64): eyJzdWIiOiJyYWplc2gtMDAxIiwibmFtZSI6Il...
Signature: UlMyNTYtU0lHTkFUVVJFLUJZVEVT
Decoded Header: {"alg":"RS256","typ":"JWT"}
Decoded Payload: {"sub":"rajesh-001","name":"Rajesh Kumar","roles":["ROLE_CUSTOMER","ROLE_TRANSFER"],"iat":1719849600,"exp":1719853200,"iss":"https://auth.nationalbankofindia.com"}
Key claims:
sub (subject): rajesh-001 (unique user ID)
roles: ROLE_CUSTOMER, ROLE_TRANSFER
iat (issued at): 1719849600 (Unix timestamp)
exp (expires): 1719853200 (1 hour later)
iss (issuer): https://auth.nationalbankofindia.com
How is RS256 different from HS256?
| Feature | HS256 (HMAC-SHA256) | RS256 (RSA-SHA256) |
|---|---|---|
| Key type | Shared secret (symmetric) | Public/private key pair (asymmetric) |
| Who signs? | Anyone with the secret | Only the authorization server (private key) |
| Who verifies? | Anyone with the same secret | Any service with the public key |
| Security risk | If one service is compromised, the secret is leaked and any service can forge tokens | If a resource server is compromised, only the public key is leaked; tokens cannot be forged |
| Key distribution | Must securely share secret with every service | Only distribute the public key (safe to expose) |
| Performance | Faster (symmetric crypto) | Slower (asymmetric crypto), but verification is fast |
| Microservices fit | Bad (shared secret is a single point of compromise) | Good (each service only needs the public key) |
package com.bank.security;
public class HS256vsRS256 {
public static void main(String[] args) {
System.out.println("=== HS256 (Symmetric) ===");
System.out.println(" auth-service signs with: SECRET_KEY_123");
System.out.println(" account-service verifies with: SECRET_KEY_123 (SAME key)");
System.out.println(" transfer-service verifies with: SECRET_KEY_123 (SAME key)");
System.out.println(" Risk: if account-service is hacked, attacker has the key");
System.out.println(" and can forge tokens for any user.");
System.out.println();
System.out.println("=== RS256 (Asymmetric) ===");
System.out.println(" auth-service signs with: PRIVATE KEY (kept secret)");
System.out.println(" account-service verifies with: PUBLIC KEY (safe to share)");
System.out.println(" transfer-service verifies with: PUBLIC KEY (safe to share)");
System.out.println(" If account-service is hacked, attacker only has the public key.");
System.out.println(" They CANNOT forge tokens because they do not have the private key.");
System.out.println();
System.out.println("Recommendation: use RS256 for microservices.");
}
}
Expected output:
=== HS256 (Symmetric) ===
auth-service signs with: SECRET_KEY_123
account-service verifies with: SECRET_KEY_123 (SAME key)
transfer-service verifies with: SECRET_KEY_123 (SAME key)
Risk: if account-service is hacked, attacker has the key
and can forge tokens for any user.
=== RS256 (Asymmetric) ===
auth-service signs with: PRIVATE KEY (kept secret)
account-service verifies with: PUBLIC KEY (safe to share)
transfer-service verifies with: PUBLIC KEY (safe to share)
If account-service is hacked, attacker only has the public key.
They CANNOT forge tokens because they do not have the private key.
Recommendation: use RS256 for microservices.
What is the token flow in a microservices architecture?
The flow has four steps:
- The client (mobile app or browser) sends credentials to the authorization server.
- The authorization server validates credentials and returns a JWT access token (and optionally a refresh token).
- The client sends the access token in the Authorization header with every API request.
- The resource server (account-service) validates the token signature and expiration, extracts claims, and authorizes the request.
package com.bank.security;
public class TokenFlowDemo {
record TokenFlowStep(int step, String actor, String action, String detail) {}
public static void main(String[] args) {
var steps = java.util.List.of(
new TokenFlowStep(1, "Rajesh (client)",
"POST /auth/login",
"Sends username=rajesh, password=****** to auth-service"),
new TokenFlowStep(2, "auth-service",
"Validate credentials",
"Checks username/password against database. If valid, create JWT."),
new TokenFlowStep(3, "auth-service",
"Return JWT",
"Returns {accessToken: eyJhbG..., expiresIn: 3600, refreshToken: abc123}"),
new TokenFlowStep(4, "Rajesh (client)",
"GET /accounts/SAV2001",
"Sends Authorization: Bearer eyJhbG... to account-service"),
new TokenFlowStep(5, "account-service",
"Validate JWT",
"Verify RS256 signature with public key. Check exp > now. Extract roles."),
new TokenFlowStep(6, "account-service",
"Authorize request",
"User has ROLE_CUSTOMER. Endpoint requires ROLE_CUSTOMER. Access granted."),
new TokenFlowStep(7, "account-service",
"Return data",
"Returns {accountNumber: SAV2001, balance: 500000.00}")
);
System.out.println("JWT Token Flow in National Bank of India:");
for (var step : steps) {
System.out.println(" Step " + step.step() + " [" + step.actor() + "]");
System.out.println(" Action: " + step.action());
System.out.println(" Detail: " + step.detail());
}
}
}
Expected output:
JWT Token Flow in National Bank of India:
Step 1 [Rajesh (client)]
Action: POST /auth/login
Detail: Sends username=rajesh, password=****** to auth-service
Step 2 [auth-service]
Action: Validate credentials
Detail: Checks username/password against database. If valid, create JWT.
Step 3 [auth-service]
Action: Return JWT
Detail: Returns {accessToken: eyJhbG..., expiresIn: 3600, refreshToken: abc123}
Step 4 [Rajesh (client)]
Action: GET /accounts/SAV2001
Detail: Sends Authorization: Bearer eyJhbG... to account-service
Step 5 [account-service]
Action: Validate JWT
Detail: Verify RS256 signature with public key. Check exp > now. Extract roles.
Step 6 [account-service]
Action: Authorize request
Detail: User has ROLE_CUSTOMER. Endpoint requires ROLE_CUSTOMER. Access granted.
Step 7 [account-service]
Action: Return data
Detail: Returns {accountNumber: SAV2001, balance: 500000.00}
What is a complete banking project with JWT security?
This project has two services: auth-service (issues JWTs) and account-service (validates JWTs and returns protected data). The auth-service uses RSA key pair for RS256 signing. The account-service uses Spring Security's resource server support to validate tokens.
Project structure
jwt-banking-security/
├── docker-compose.yml
├── init-db.sql
├── auth-service/
│ ├── pom.xml
│ └── src/main/
│ ├── java/com/bank/auth/
│ │ ├── AuthServiceApp.java
│ │ ├── controller/AuthController.java
│ │ ├── service/AuthService.java
│ │ ├── service/JwtTokenProvider.java
│ │ ├── model/BankUser.java
│ │ ├── dto/LoginRequest.java
│ │ ├── dto/TokenResponse.java
│ │ ├── repository/UserRepository.java
│ │ └── config/SecurityConfig.java
│ └── resources/
│ ├── application.yml
│ ├── app.key (RSA private key)
│ └── app.pub (RSA public key)
└── account-service/
├── pom.xml
└── src/main/
├── java/com/bank/account/
│ ├── AccountServiceApp.java
│ ├── controller/AccountController.java
│ ├── service/AccountService.java
│ ├── model/Account.java
│ ├── dto/AccountResponse.java
│ ├── repository/AccountRepository.java
│ ├── config/SecurityConfig.java
│ └── config/JwtDecoderConfig.java
└── resources/
├── application.yml
└── app.pub (same RSA public key)
auth-service pom.xml
<?xml version="1.0" encoding="UTF-8"?syn-kw">>
syn-kw"><project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd"syn-kw">>
syn-kw"><modelVersionsyn-kw">>4.0.0syn-kw"></modelVersionsyn-kw">>
syn-kw"><parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-parentsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>3.4.1syn-kw"></versionsyn-kw">>
syn-kw"></parentsyn-kw">>
syn-kw"><groupIdsyn-kw">>com.banksyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>auth-servicesyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>1.0.0syn-kw"></versionsyn-kw">>
syn-kw"><propertiessyn-kw">>
syn-kw"><java.versionsyn-kw">>25syn-kw"></java.versionsyn-kw">>
syn-kw"></propertiessyn-kw">>
syn-kw"><dependenciessyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-websyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-securitysyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.springframework.bootsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>spring-boot-starter-data-jpasyn-kw"></artifactIdsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.jsonwebtokensyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jjwt-apisyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>0.12.6syn-kw"></versionsyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.jsonwebtokensyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jjwt-implsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>0.12.6syn-kw"></versionsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>io.jsonwebtokensyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>jjwt-jacksonsyn-kw"></artifactIdsyn-kw">>
syn-kw"><versionsyn-kw">>0.12.6syn-kw"></versionsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"><dependencysyn-kw">>
syn-kw"><groupIdsyn-kw">>org.postgresqlsyn-kw"></groupIdsyn-kw">>
syn-kw"><artifactIdsyn-kw">>postgresqlsyn-kw"></artifactIdsyn-kw">>
syn-kw"><scopesyn-kw">>runtimesyn-kw"></scopesyn-kw">>
syn-kw"></dependencysyn-kw">>
syn-kw"></dependenciessyn-kw">>
syn-kw"></projectsyn-kw">>
JwtTokenProvider.java (creates signed JWT with RS256)
package com.bank.auth.service;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import jakarta.annotation.PostConstruct;
import java.nio.file.Files;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;
@Component
public class JwtTokenProvider {
private static final Logger LOG = Logger.getLogger(JwtTokenProvider.class.getName());
private static final long ACCESS_TOKEN_VALIDITY_MS = 3600_000; // 1 hour
private static final long REFRESH_TOKEN_VALIDITY_MS = 86400_000; // 24 hours
@Value("classpath:app.key")
private Resource privateKeyResource;
private PrivateKey privateKey;
@PostConstruct
public void init() throws Exception {
var keyContent = new String(Files.readAllBytes(privateKeyResource.getFile().toPath()));
var keyPem = keyContent
.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s", "");
var keyBytes = Base64.getDecoder().decode(keyPem);
var keySpec = new PKCS8EncodedKeySpec(keyBytes);
this.privateKey = KeyFactory.getInstance("RSA").generatePrivate(keySpec);
LOG.info("RSA private key loaded for JWT signing");
}
public String createAccessToken(String userId, String name, List<String> roles) {
var now = new Date();
var expiry = new Date(now.getTime() + ACCESS_TOKEN_VALIDITY_MS);
return Jwts.builder()
.subject(userId)
.claim("name", name)
.claim("roles", roles)
.issuer("https://auth.nationalbankofindia.com")
.issuedAt(now)
.expiration(expiry)
.signWith(privateKey)
.compact();
}
public String createRefreshToken(String userId) {
var now = new Date();
var expiry = new Date(now.getTime() + REFRESH_TOKEN_VALIDITY_MS);
return Jwts.builder()
.subject(userId)
.claim("type", "refresh")
.issuer("https://auth.nationalbankofindia.com")
.issuedAt(now)
.expiration(expiry)
.signWith(privateKey)
.compact();
}
}
LoginRequest.java and TokenResponse.java
package com.bank.auth.dto;
public record LoginRequest(String username, String password) {}
package com.bank.auth.dto;
public record TokenResponse(
String accessToken,
String refreshToken,
long expiresIn,
String tokenType
) {}
AuthService.java
package com.bank.auth.service;
import com.bank.auth.dto.TokenResponse;
import com.bank.auth.model.BankUser;
import com.bank.auth.repository.UserRepository;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.logging.Logger;
@Service
public class AuthService {
private static final Logger LOG = Logger.getLogger(AuthService.class.getName());
private final UserRepository userRepository;
private final JwtTokenProvider tokenProvider;
private final PasswordEncoder passwordEncoder;
public AuthService(UserRepository userRepository,
JwtTokenProvider tokenProvider,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.tokenProvider = tokenProvider;
this.passwordEncoder = passwordEncoder;
}
public TokenResponse login(String username, String password) {
var user = userRepository.findByUsername(username)
.orElseThrow(() -> new RuntimeException("Invalid credentials"));
if (!passwordEncoder.matches(password, user.getPasswordHash())) {
throw new RuntimeException("Invalid credentials");
}
var roles = List.of(user.getRole().split(","));
var accessToken = tokenProvider.createAccessToken(user.getUserId(), user.getFullName(), roles);
var refreshToken = tokenProvider.createRefreshToken(user.getUserId());
LOG.info("Login successful: userId=" + user.getUserId() + ", roles=" + roles);
return new TokenResponse(accessToken, refreshToken, 3600, "Bearer");
}
}
AuthController.java
package com.bank.auth.controller;
import com.bank.auth.dto.LoginRequest;
import com.bank.auth.dto.TokenResponse;
import com.bank.auth.service.AuthService;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
@RequestMapping("/auth")
public class AuthController {
private final AuthService authService;
public AuthController(AuthService authService) {
this.authService = authService;
}
@PostMapping("/login")
public ResponseEntity<TokenResponse> login(@RequestBody LoginRequest request) {
var response = authService.login(request.username(), request.password());
return ResponseEntity.ok(response);
}
}
SecurityConfig.java (auth-service, permits /auth/** without authentication)
package com.bank.auth.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/auth/**").permitAll()
.anyRequest().authenticated()
)
.build();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
account-service SecurityConfig.java (resource server, validates JWT)
package com.bank.account.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.web.SecurityFilterChain;
@Configuration
public class SecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
return http
.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(auth -> auth
.requestMatchers("/accounts/**").hasAuthority("SCOPE_ROLE_CUSTOMER")
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth2 -> oauth2.jwt(jwt -> {}))
.build();
}
}
account-service application.yml
server:
port: 8081
spring:
application:
name: account-service
datasource:
url: jdbc:postgresql://localhost:5432/bank
username: bank
password: bank123
jpa:
hibernate:
ddl-auto: none
security:
oauth2:
resourceserver:
jwt:
public-key-location: classpath:app.pub
How to generate RSA key pair
# Generate RSA private key (PKCS8 format)
openssl genpkey -algorithm RSA -out app.key -pkeyopt rsa_keygen_bits:2048
# Extract public key
openssl rsa -in app.key -pubout -out app.pub
# Copy both files to auth-service/src/main/resources/
# Copy app.pub to account-service/src/main/resources/
Expected output:
app.key: RSA private key (PEM format, keep secret)
app.pub: RSA public key (PEM format, safe to distribute)
How to run and test
# Step 1: Start PostgreSQL
docker-compose up -d postgres
# Step 2: Build and start auth-service
cd auth-service && mvn clean package -DskipTests && cd ..
java -jar auth-service/target/auth-service-1.0.0.jar &
# Step 3: Build and start account-service
cd account-service && mvn clean package -DskipTests && cd ..
java -jar account-service/target/account-service-1.0.0.jar &
# Step 4: Login to get JWT
TOKEN=$(curl -s -X POST http://localhost:8080/auth/login \
-H "Content-Type: application/json" \
-d '{"username":"rajesh","password":"rajesh123"}' | jq -r '.accessToken')
echo "JWT Token: ${TOKEN:0:50}..."
# Step 5: Call protected API with token
curl -s http://localhost:8081/accounts/SAV2001 \
-H "Authorization: Bearer $TOKEN"
# Step 6: Call without token (should get 401)
curl -s -o /dev/null -w "%{http_code}" http://localhost:8081/accounts/SAV2001
Expected output (Step 4, login):
{
"accessToken": "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJyYWplc2gtMDAxIi...",
"refreshToken": "eyJhbGciOiJSUzI1NiJ9.eyJzdWIiOiJyYWplc2gtMDAxIi...",
"expiresIn": 3600,
"tokenType": "Bearer"
}
Expected output (Step 5, with valid token):
{"accountNumber":"SAV2001","holderName":"Rajesh Kumar","balance":500000.00}
Expected output (Step 6, without token):
401 (Unauthorized)
How do services propagate tokens to each other?
When transfer-service calls account-service, it must forward the JWT token from the original request. The client's token is extracted from the incoming request's Authorization header and added to the outgoing RestClient call.
In Spring Boot, you can use a ClientHttpRequestInterceptor on the RestClient to automatically copy the token from the current security context to outgoing requests.
package com.bank.transfer.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.client.RestClient;
@Configuration
public class RestClientConfig {
@Bean
public RestClient accountRestClient() {
return RestClient.builder()
.baseUrl("http://localhost:8081")
.requestInterceptor((request, body, execution) -> {
var auth = SecurityContextHolder.getContext().getAuthentication();
if (auth instanceof JwtAuthenticationToken jwtAuth) {
var token = jwtAuth.getToken().getTokenValue();
request.getHeaders().setBearerAuth(token);
}
return execution.execute(request, body);
})
.build();
}
}
Expected output (conceptual):
transfer-service receives: Authorization: Bearer eyJhbG...
transfer-service extracts token from SecurityContext
transfer-service calls account-service with same token:
GET http://account-service:8081/accounts/SAV2001
Authorization: Bearer eyJhbG...
account-service validates token and returns account data
What are common mistakes with JWT security?
Wrong: storing JWT in localStorage (XSS vulnerable)
package com.bank.security.wrong;
public class WrongJwtStorage {
public static void main(String[] args) {
System.out.println("WRONG: storing JWT in browser localStorage");
System.out.println();
System.out.println(" JavaScript: localStorage.setItem('token', jwt)");
System.out.println();
System.out.println(" Risk: Cross-Site Scripting (XSS) attack");
System.out.println(" Any JavaScript on the page can read localStorage.");
System.out.println(" If an attacker injects a script (XSS), they steal the token.");
System.out.println(" With the token, they can call APIs as the victim.");
System.out.println();
System.out.println("CORRECT: store JWT in HttpOnly, Secure, SameSite cookie");
System.out.println(" HttpOnly: JavaScript cannot read the cookie");
System.out.println(" Secure: cookie sent only over HTTPS");
System.out.println(" SameSite=Strict: cookie not sent with cross-site requests");
}
}
Expected output:
WRONG: storing JWT in browser localStorage
JavaScript: localStorage.setItem('token', jwt)
Risk: Cross-Site Scripting (XSS) attack
Any JavaScript on the page can read localStorage.
If an attacker injects a script (XSS), they steal the token.
With the token, they can call APIs as the victim.
CORRECT: store JWT in HttpOnly, Secure, SameSite cookie
HttpOnly: JavaScript cannot read the cookie
Secure: cookie sent only over HTTPS
SameSite=Strict: cookie not sent with cross-site requests
Wrong: no token expiration or very long expiration
package com.bank.security.wrong;
public class WrongTokenExpiration {
public static void main(String[] args) {
System.out.println("WRONG: access token valid for 30 days");
System.out.println(" If the token is stolen, the attacker has 30 days of access.");
System.out.println(" You cannot revoke a JWT (it is self-contained).");
System.out.println();
System.out.println("CORRECT: short-lived access token + refresh token");
System.out.println(" Access token: 15-60 minutes (short-lived, used for API calls)");
System.out.println(" Refresh token: 24 hours to 7 days (used only to get new access tokens)");
System.out.println(" If access token is stolen: damage limited to 60 minutes");
System.out.println(" If refresh token is stolen: revoke it in the database");
}
}
Expected output:
WRONG: access token valid for 30 days
If the token is stolen, the attacker has 30 days of access.
You cannot revoke a JWT (it is self-contained).
CORRECT: short-lived access token + refresh token
Access token: 15-60 minutes (short-lived, used for API calls)
Refresh token: 24 hours to 7 days (used only to get new access tokens)
If access token is stolen: damage limited to 60 minutes
If refresh token is stolen: revoke it in the database
What should a senior or principal engineer know?
- At the senior level:
- Token revocation: JWTs are stateless, so you cannot revoke them by deleting a session. Use short expiration times and a token blacklist (Redis set of revoked token IDs checked on each request) for immediate revocation when needed.
- Scope vs. Role: OAuth 2.0 scopes define what actions a token allows (read:accounts, write:transfers). Roles define who the user is (ROLE_ADMIN, ROLE_CUSTOMER). Use scopes for API-level authorization and roles for business-level authorization.
- JWKS endpoint: instead of distributing the public key file, the authorization server exposes a /.well-known/jwks.json endpoint. Resource servers fetch the public key from this endpoint and cache it. This enables key rotation without redeploying services.
- At the principal level:
- Key rotation: rotate RSA keys periodically (every 90 days). The authorization server signs new tokens with the new key while resource servers still accept tokens signed with the old key (grace period). Use the kid (Key ID) header in the JWT to identify which key was used.
- Service-to-service auth: use OAuth 2.0 client_credentials grant for service-to-service communication. Each service has its own client ID and secret. The authorization server issues a token scoped to the specific service.
- Zero trust: do not trust any service just because it is inside the network. Every service must validate the JWT on every request.
package com.bank.security;
public class SeniorJwtKnowledge {
public static void main(String[] args) {
System.out.println("Senior/Principal JWT security checklist:");
System.out.println(" 1. Use RS256 (asymmetric), not HS256 (symmetric)");
System.out.println(" 2. Short access token (15-60 min), longer refresh token (24h-7d)");
System.out.println(" 3. Store tokens in HttpOnly, Secure, SameSite cookies");
System.out.println(" 4. Use JWKS endpoint for public key distribution");
System.out.println(" 5. Rotate RSA keys every 90 days, use kid header");
System.out.println(" 6. Token blacklist in Redis for immediate revocation");
System.out.println(" 7. Use scopes for API access, roles for business rules");
System.out.println(" 8. client_credentials grant for service-to-service auth");
System.out.println(" 9. Validate issuer (iss) and audience (aud) claims");
System.out.println(" 10. Zero trust: validate JWT on every request, even internal");
}
}
Expected output:
Senior/Principal JWT security checklist:
1. Use RS256 (asymmetric), not HS256 (symmetric)
2. Short access token (15-60 min), longer refresh token (24h-7d)
3. Store tokens in HttpOnly, Secure, SameSite cookies
4. Use JWKS endpoint for public key distribution
5. Rotate RSA keys every 90 days, use kid header
6. Token blacklist in Redis for immediate revocation
7. Use scopes for API access, roles for business rules
8. client_credentials grant for service-to-service auth
9. Validate issuer (iss) and audience (aud) claims
10. Zero trust: validate JWT on every request, even internal
What are common interview follow-up questions?
- What is the difference between authentication and authorization? (Authentication verifies who you are. Authorization verifies what you are allowed to do. JWT carries both: the sub claim identifies the user, and the roles/scopes claims define permissions.)
- How do you handle token refresh? (The client sends the refresh token to a dedicated /auth/refresh endpoint. The server validates the refresh token, checks it is not revoked, and issues a new access token. The old access token continues to work until it expires.)
- What is OIDC and how does it relate to OAuth 2.0? (OpenID Connect is a layer on top of OAuth 2.0 that adds authentication. OAuth 2.0 is about authorization (access to resources). OIDC adds an ID token that contains user identity claims like name and email.)
- Can you use JWT without OAuth 2.0? (Yes. You can issue JWTs from a simple login endpoint without implementing the full OAuth 2.0 protocol. Many internal systems do this. OAuth 2.0 adds standardized flows for third-party access.)
- What happens when the authorization server is down? (Resource servers can still validate tokens because JWTs are self-contained. The public key is cached locally. New logins will fail, but existing tokens continue to work until they expire.)
Visual Overview
JWT Authentication Flow in Microservices
==========================================
┌───────────┐ ┌──────────────┐ ┌──────────────────┐
│ Client │ │ auth-service │ │ account-service │
│ (browser) │ │ (port 8080) │ │ (port 8081) │
└─────┬─────┘ └──────┬───────┘ └────────┬──────────┘
│ │ │
│ POST /auth/login │ │
│ {user, password} │ │
│─────────────────>│ │
│ │ │
│ │ Validate credentials │
│ │ Create JWT (RS256) │
│ │ Sign with PRIVATE KEY│
│ │ │
│ {accessToken, │ │
│ refreshToken} │ │
│<─────────────────│ │
│ │ │
│ GET /accounts/SAV2001 │
│ Authorization: Bearer eyJhbG... │
│────────────────────────────────────────>│
│ │
│ Verify signature │
│ with PUBLIC KEY │
│ Check exp > now │
│ Extract roles │
│ Check ROLE_CUSTOMER │
│ │
│ {accountNumber: SAV2001, │
│ balance: 500000.00} │
│<────────────────────────────────────────│
Key Distribution
=================
auth-service: has PRIVATE KEY (signs tokens)
account-service: has PUBLIC KEY (verifies tokens)
transfer-service: has PUBLIC KEY (verifies tokens)
The public key is safe to distribute.
Only auth-service can create valid tokens.
Key Takeaway
OAuth 2.0 is an authorization framework that separates the concerns of authentication and resource access. In a microservices architecture, a central authorization server issues JWT tokens after verifying user credentials. Each resource server validates the token independently using the authorization server's public key, without making a network call back to the authorization server.
A JWT contains three parts: a header (algorithm), a payload (user ID, roles, expiration), and a signature. The signature is created with the authorization server's RSA private key and verified with the corresponding public key. This asymmetric approach (RS256) means that even if a resource server is compromised, the attacker cannot forge tokens because they only have the public key.
In our National Bank of India project, Rajesh logged in to auth-service with his credentials. The auth-service validated the password, created a JWT with claims (sub: rajesh-001, roles: ROLE_CUSTOMER), signed it with the RSA private key, and returned it. Rajesh's mobile banking app then called account-service with the JWT in the Authorization header. The account-service verified the signature with the public key, checked the expiration, extracted the ROLE_CUSTOMER role, and returned the account balance.
For service-to-service communication, the JWT from the original request is propagated through the call chain. The transfer-service receives a JWT from the client, extracts it from the security context, and attaches it to outgoing calls to account-service. This way, account-service always knows who the original user is and what permissions they have, regardless of which service is calling.
At the senior level, use short-lived access tokens (15-60 minutes), JWKS endpoints for public key distribution, and token blacklists in Redis for immediate revocation. At the principal level, implement key rotation every 90 days and use the client_credentials grant for machine-to-machine authentication.
Remember one sentence: JWT is a self-contained token signed with a private key and verified with a public key, so every microservice can validate the token without calling the authorization server.
---