🚀 Modern Security Guide for Java Developers

Published: (December 2, 2025 at 12:48 PM EST)
3 min read
Source: Dev.to

Source: Dev.to

Zero‑Trust Rules – Verify WHO the user is, verify WHAT they can access, and trust nothing implicitly, even inside your VPC.

Core Flow

Client → API Gateway → Authorization Server → Resource Server

Zero‑Trust Rules

  • Verify WHO the user is.
  • Verify WHAT they can access.
  • No implicit trust — even inside your VPC.
  • Tokens should always be short‑lived.

JWT — Use Asymmetric Keys (RS256)

Key Strategy

  • Private Key: Stays only in the Authorization Server.
  • Public Key: Shared to the Gateway and microservices for validation.

Step 1: Generate RSA Keys

openssl genrsa -out private.pem 4096
openssl rsa -in private.pem -pubout -out public.pem

Step 2: Spring Boot JWT Validation (Public Key)

@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));
}

Defense List – Secure HTTP Headers

  • Content‑Security‑Policy (CSP): Blocks malicious JS injections (prevents most XSS).
  • Strict‑Transport‑Security (HSTS): Forces HTTPS and stops SSL downgrades.
  • X‑Frame‑Options: Disables framing to prevent clickjacking.
  • X‑Content‑Type‑Options: Blocks MIME sniffing.

Secure Header Configuration (Spring Security)

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

CSRF Settings

  • When using JWT in headers: Disable CSRF (the token already protects against it).
http.csrf(csrf -> csrf.disable());
  • When using cookie‑based authentication: Enable CSRF protection.

Input Validation & Sanitization

// Example using Google's JSON Sanitizer (or similar)
String sanitized = JsonSanitizer.sanitize(userInput);

// Log sanitized data only
log.info("User input: {}", sanitized);

// Simple length check
if (userInput.length() > 200) {
    throw new BadRequestException();
}

API Gateway Responsibilities

Flow: Client → WAF → Load Balancer → API Gateway → Microservices

  • Centralized authentication
  • JWT validation
  • Rate limiting & IP blocklists
  • Route isolation

Spring Cloud Gateway Token Relay Example

spring:
  cloud:
    gateway:
      routes:
        - id: secure-service
          uri: http://localhost:8082
          predicates:
            - Path=/secure/**
          filters:
            - RemoveRequestHeader=Cookie
            - TokenRelay

Stateless architecture – stickiness is unnecessary when JWT is used.

Client
   |
Load Balancer

Microservice A ↔ Microservice B

Actuator Exposure

Avoid leaking full system metadata. Configure exposure explicitly:

management.endpoints.web.exposure.include=health,info
management.endpoints.web.exposure.exclude=env,beans

Password Encoding

Never implement your own cryptography. Use BCrypt, which is intentionally slow to resist brute‑force attacks.

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder(12);
}

Enterprise Control List (Layered Security)

LayerFocus
1 – PerimeterWAF, DDoS mitigation
2 – NetworkZero‑Trust, TLS 1.3
3 – GatewayAuth, rate limits
4 – ApplicationOAuth2, JWT RS256
5 – HeadersCSP, HSTS, X‑Frame‑Options
6 – CodeInput validation
7 – SecretsVault / AWS Secrets Manager
8 – MonitoringSIEM, audit logs

Architectural Blueprint

📱 Client
   ↓ (TLS 1.3)
🌐 API Gateway (JWT validation, throttling)

🔐 Microservices (RBAC + scopes)

🗄 Encrypted Database (least‑privilege access)

Takeaway

Most projects secure only the login page. Enterprise‑grade systems require protection at every layer. Implementing even half of the practices outlined here puts you ahead of the majority of developers. 🚀

Back to Blog

Related posts

Read more »

Java OOPS Concepts

!Forem Logohttps://media2.dev.to/dynamic/image/width=65,height=,fit=scale-down,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%...