Subtitle: OAuth 2.0, JWT, Asymmetric Encryption, Zero-Trust, Hardening Headers, API Gateway, & Load Balancers.
Most developers think security ends at:
Login β JWT β Authenticated β
But enterprise-grade systems demand multi-layer security + zero-trust enforcement. π‘οΈ
Here is a practical, production-ready guide to hardening your Java architecture.
π 1. OAuth 2.0 + Zero-Trust: Foundation of Modern Auth
OAuth 2.0 is authorization, not authentication.
Your backend must treat every request as hostile.
π Core Flow:
Client β API Gateway β Authorization Server β Resource Server
π§ Zero-Trust Rules:
β Always verify WHO the user is.
β Always verify WHAT they can access.
β No implicit trust β even inside your VPC.
β Tokens should always be short-lived.
π 2. JWT β Use Asymmetric Keys (RS256)
HS256 = Risky shared secret β
RS256 = Private signing + Public verification β
The Key Strategy:
Private Key: Stays only in the Authorization Server.
Public Key: Shared to Gateway + Microservices for validation.
π Step 1: Generate RSA Keys
Bash
openssl genrsa -out private.pem 4096
openssl rsa -in private.pem -pubout -out public.pem
π Step 2: Spring Boot JWT Validation (Public Key)
Java
@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.authorizeHttpRequests(auth -> auth
.requestMatchers("/public/**").permitAll()
.anyRequest().authenticated()
)
.oauth2ResourceServer(oauth -> oauth
.jwt(jwt -> jwt.publicKey(publicKey()))
)
.sessionManagement(session -> session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
);
return http.build();
}
@Bean
public RSAPublicKey publicKey() throws Exception {
String key = Files.readString(Path.of("public.pem"))
.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s", "");
byte[] decoded = Base64.getDecoder().decode(key);
return (RSAPublicKey) KeyFactory
.getInstance("RSA")
.generatePublic(new X509EncodedKeySpec(decoded));
}
π‘οΈ 3. Hardening with Security Headers
Spring Security defaults are good, but enterprise apps need explicit hardening.
The Defense List:
CSP (Content Security Policy): Blocks malicious JS injections (Prevents 95% of XSS).
HSTS: Forces HTTPS and stops SSL downgrades.
X-Frame-Options: Disables framing to prevent Clickjacking.
X-Content-Type-Options: Blocks MIME sniffing (drive-by attacks).
π§ Secure Header Config:
Java
http.headers(headers -> headers
.contentSecurityPolicy(csp -> csp
.policyDirectives("default-src 'self'; script-src 'self'")
)
.xssProtection(xss -> xss.block(true))
.frameOptions(HeadersConfigurer.FrameOptionsConfig::deny)
.httpStrictTransportSecurity(hsts -> hsts
.includeSubDomains(true)
.maxAgeInSeconds(31536000)
)
.contentTypeOptions(Customizer.withDefaults())
);
π§ͺ 4. CSRF Protection β Correct Usage
Most devs misconfigure this. The rule is simple:
β If using JWT in headers:
Disable CSRF. The token prevents the attack.
Java
http.csrf(csrf -> csrf.disable());
β If using Cookie-based auth:
You MUST enable CSRF.
π§Ό 5. Prevent XSS β Sanitize User Input
Never trust UI inputs. Never log raw data from users.
Validate length.
Remove scripts.
Java
// Google's JSON Sanitizer or similar library
String sanitized = JsonSanitizer.sanitize(userInput);
// Logging sanitized data only
log.info("User input: {}", sanitized);
if (input.length() > 200) throw new BadRequestException();
π 6. API Gateway β First Security Checkpoint
Your Gateway is your bouncer.
Flow: Client β WAF β Load Balancer β API Gateway β Microservices
Gateway Responsibilities:
Centralized Auth
JWT validation
Rate-limits & IP blocklists
Route isolation
Example β Spring Cloud Gateway Token Relay:
YAML
spring:
cloud:
gateway:
routes:
- id: secure-service
uri: http://localhost:8082
predicates:
- Path=/secure/**
filters:
- RemoveRequestHeader=Cookie
- TokenRelay
βοΈ 7. Stateless Load Balancing
Stickiness is not needed when using JWT. This allows your microservices to remain lightweight and scalable.
Plaintext
Client
|
Load Balancer
β
Microservice A β Microservice B
(Stateless Architecture)
π« 8. Block Dangerous Actuator Endpoints
If you expose Actuator without filtering, you are leaking full system metadata.
application.properties:
Properties
management.endpoints.web.exposure.include=health,info
management.endpoints.web.exposure.exclude=env,beans
π 9. Password Encryption
Never roll your own crypto. Use BCrypt. It is slow by design, making it secure against brute-force attacks.
Java
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder(12);
}
π§© 10. Full Security Architecture
A complete enterprise control list looks like this:
Layer 1 (Perimeter): WAF, DDoS Mitigation.
Layer 2 (Network): Zero-Trust, TLS 1.3.
Layer 3 (Gateway): Auth, Rate limits.
Layer 4 (Application): OAuth2, JWT RS256.
Layer 5 (Headers): CSP, HSTS, X-Frame-Options.
Layer 6 (Code): Input Validation.
Layer 7 (Secrets): Vault / AWS Secrets Manager.
Layer 8 (Monitoring): SIEM, Audit Logs.
πΊοΈ The Architectural Blueprint
π± Client
β (TLS 1.3)
π API Gateway (JWT validation, throttling)
β
π Microservices (RBAC + Scopes)
β
π Encrypted Database (Least Privilege Access)
π― Final Takeaway
Most projects secure only the login page.
Enterprise systems require security at EVERY layer.
If you adopt even 50% of this guide, youβll already be ahead of 90% of developers. π
Top comments (0)