DEV Community

PRASAD NAIK
PRASAD NAIK

Posted on

πŸš€ Modern Security Guide for Java Developers

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:

  1. Private Key: Stays only in the Authorization Server.

  2. 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

Enter fullscreen mode Exit fullscreen mode

πŸ”Ž 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));
}

Enter fullscreen mode Exit fullscreen mode

πŸ›‘οΈ 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())
);

Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ 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());

Enter fullscreen mode Exit fullscreen mode

⚠ 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.

  1. Validate length.

  2. 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();

Enter fullscreen mode Exit fullscreen mode

🌐 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

Enter fullscreen mode Exit fullscreen mode

βš™οΈ 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)

Enter fullscreen mode Exit fullscreen mode

🚫 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

Enter fullscreen mode Exit fullscreen mode

πŸ” 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);
}

Enter fullscreen mode Exit fullscreen mode

🧩 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)

Enter fullscreen mode Exit fullscreen mode

🎯 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)