Ten Java Security Patterns Every Developer Must Know to Prevent Costly Breaches and Audit Failures

Secure your Java apps with 10 proven habits: JWT validation, Argon2 hashing, AES-GCM encryption, and more. Build safer code today.

Ten Java Security Patterns Every Developer Must Know to Prevent Costly Breaches and Audit Failures

I once shipped a Java service that stored passwords with MD5. The code compiled. The tests passed. Nobody complained for two years. Then an auditor flagged it, and I spent a weekend rewriting authentication across four services. That weekend taught me more about security than any conference talk. Since then, I’ve kept a short list of habits I reuse whenever I build something that touches user data, money, or identity.

The word “pattern” can sound academic. I think of a pattern as a habit you repeat without thinking. When you’ve written the same safe code ten times, the eleventh time costs no effort. That is what this article is about. Ten habits that make a Java application harder to break, written in language a beginner can follow.

Let me start with authentication, because most attacks begin there.

1. Always Validate a JSON Web Token Before You Trust It

A JSON Web Token looks like three base64 chunks glued together with dots. The first chunk is a header. The second is the payload, which anyone can read because it is only base64-encoded, not encrypted. The third is a signature. If you skip signature validation, an attacker can change the payload to say “role”: “ADMIN” and your server will believe it.

This is the single most common JWT mistake I’ve seen. I’ve made it myself. You decode the token, read the claims, and forget to verify the signature. Never do that.

Here is a small service I use in Spring Boot projects. I keep the secret in a config property, never in source code.

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import javax.crypto.SecretKey;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.List;

public class TokenService {

    private final SecretKey key;

    public TokenService(String base64Secret) {
        this.key = Keys.hmacShaKeyFor(java.util.Base64.getDecoder().decode(base64Secret));
    }

    public String issue(String userId, List<String> roles) {
        return Jwts.builder()
            .setSubject(userId)
            .setIssuer("my-app")
            .claim("roles", roles)
            .setIssuedAt(new Date())
            .setExpiration(Date.from(Instant.now().plus(15, ChronoUnit.MINUTES)))
            .signWith(key)
            .compact();
    }

    public Claims verify(String token) {
        try {
            return Jwts.parserBuilder()
                .setSigningKey(key)
                .requireIssuer("my-app")
                .build()
                .parseClaimsJws(token)
                .getBody();
        } catch (JwtException e) {
            throw new AuthenticationException("Bad token", e);
        }
    }
}

Notice the expiry. Fifteen minutes is short on purpose. Access tokens should be short-lived, and you should use a refresh token for longer sessions. Notice the issuer check. It stops a token minted for another service from working here.

Never use the “none” algorithm. Never trust the header’s alg field; let the library decide based on your key.

2. Let Spring Security Handle OAuth2 Resource Server Duties

If your service accepts tokens from an identity provider like Keycloak, Auth0, or Okta, you don’t need to parse JWTs yourself. Spring Security’s resource server support does the heavy lifting: fetches the JWK set, validates signatures, checks expiry, and exposes the claims.

Here is the config I copy into most services.

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Bean
    SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            .csrf(csrf -> csrf.disable())
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/public/**").permitAll()
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth -> oauth
                .jwt(jwt -> jwt
                    .jwkSetUri("https://idp.example.com/.well-known/jwks.json")
                    .jwtAuthenticationConverter(jwtAuthConverter())));
        return http.build();
    }

    private Converter<Jwt, AbstractAuthenticationToken> jwtAuthConverter() {
        JwtGrantedAuthoritiesConverter grants = new JwtGrantedAuthoritiesConverter();
        grants.setAuthoritiesClaimName("roles");
        grants.setAuthorityPrefix("ROLE_");

        JwtAuthenticationConverter converter = new JwtAuthenticationConverter();
        converter.setJwtGrantedAuthoritiesConverter(grants);
        return converter;
    }
}

The point of using this over a hand-rolled filter is the JWK set URI. When your identity provider rotates its signing keys, Spring picks up the new keys automatically. Hand-rolled validation breaks in production when keys rotate, and you spend a Saturday morning figuring out why.

3. Enforce Role-Based Access Control at the Method Level

Authentication proves who you are. Authorization decides what you can do. The best place to enforce authorization is close to the operation, not at the controller layer only. If someone adds a new endpoint three months from now, the method-level rule still protects the underlying service.

I annotate service methods with @PreAuthorize and keep the expressions simple.

@Service
public class AccountService {

    @PreAuthorize("hasRole('TELLER') or #account.ownerId == authentication.name")
    public Account view(Account account) {
        return account;
    }

    @PreAuthorize("hasRole('ADMIN')")
    public void close(Long accountId) {
        // only admins can close
    }
}

You must enable method security first.

@Configuration
@EnableMethodSecurity
public class MethodSecurityConfig { }

If you are not using Spring, write a small helper that reads the current principal and checks ownership. Say it out loud in code: “Can this user touch this row?” That single question catches most IDOR bugs, where someone changes an account ID in a URL and sees another customer’s data.

4. Hash Passwords With Argon2, Not MD5, Not SHA-256

Hash functions like MD5 and SHA-256 are fast. Fast is bad for passwords. A graphics card can compute billions of SHA-256 hashes per second. Argon2 is deliberately slow and memory-hungry, which makes brute-force attacks expensive.

I use Bouncy Castle’s Argon2 implementation because the JDK does not include one.

import org.bouncycastle.crypto.generators.Argon2BytesGenerator;
import org.bouncycastle.crypto.params.Argon2Parameters;
import java.security.SecureRandom;
import java.util.Base64;

public class PasswordHasher {

    private static final int ITERATIONS = 3;
    private static final int MEMORY_KB = 65536;
    private static final int PARALLELISM = 4;

    public String hash(String password) {
        byte[] salt = new byte[16];
        new SecureRandom().nextBytes(salt);

        Argon2Parameters params = new Argon2Parameters.Builder(Argon2Parameters.ARGON2_id)
            .withIterations(ITERATIONS)
            .withMemoryAsKB(MEMORY_KB)
            .withParallelism(PARALLELISM)
            .withSalt(salt)
            .build();

        Argon2BytesGenerator gen = new Argon2BytesGenerator();
        gen.init(params);

        byte[] hash = new byte[32];
        gen.generateBytes(password.toCharArray(), hash);

        return "argon2id$" + ITERATIONS + "$" + MEMORY_KB + "$" + PARALLELISM + "$"
            + Base64.getEncoder().encodeToString(salt) + "$"
            + Base64.getEncoder().encodeToString(hash);
    }
}

I store all the parameters in the string. If I raise memory cost in five years, old hashes still verify with their original settings, and I can upgrade them lazily on next login. Never store the salt separately from the hash; keep them together.

5. Encrypt With AES-GCM and Shun ECB Mode

ECB mode is the classic mistake. It encrypts each 16-byte block independently, so the same plaintext block produces the same ciphertext block, every single time. Encrypt an image with ECB and you can still see its silhouette when you open the ciphertext.

GCM mode adds authentication on top of encryption, so tampering is detected. It needs a unique nonce per message. I generate it randomly and prepend it to the ciphertext.

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import java.security.SecureRandom;

public class AesGcm {

    public static byte[] encrypt(SecretKey key, byte[] plaintext, byte[] aad) throws Exception {
        byte[] iv = new byte[12];
        new SecureRandom().nextBytes(iv);

        Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
        cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
        cipher.updateAAD(aad);

        byte[] ct = cipher.doFinal(plaintext);

        byte[] out = new byte[iv.length + ct.length];
        System.arraycopy(iv, 0, out, 0, iv.length);
        System.arraycopy(ct, 0, out, iv.length, ct.length);
        return out;
    }
}

Two rules I never break. First, never reuse a nonce with the same key. Second, feed something useful into updateAAD, like the user ID or record ID, so a ciphertext cannot be swapped between records.

6. Keep Private Keys in a KeyStore, Never in Source Code

Hardcoded keys are the fastest way to appear in a security report. Even if you obfuscate your JAR, anyone with the file can run strings and find base64 blobs. Loading keys from a PKCS12 KeyStore is one small step up.

import java.security.KeyStore;
import java.nio.file.*;

KeyStore ks = KeyStore.getInstance("PKCS12");
char[] password = System.getenv("KS_PASSWORD").toCharArray();

try (InputStream in = Files.newInputStream(Path.of("keys.p12"))) {
    ks.load(in, password);
}

KeyStore.PrivateKeyEntry entry = (KeyStore.PrivateKeyEntry) ks.getEntry(
    "app-key", new KeyStore.PasswordProtection(password));
PrivateKey privateKey = entry.getPrivateKey();

The password itself comes from the environment. In real deployments I get it from a secrets manager such as AWS Secrets Manager or HashiCorp Vault, and the KeyStore never lands in a container image. The container pulls the secrets at startup, uses them, and rotates them on a schedule.

7. Use SecureRandom for Anything a User Could Predict

java.util.Random is a linear congruential generator. Given two outputs, an attacker can predict the third. That is fine for picking a dice roll in a game. It is catastrophic for session IDs, password reset tokens, and encryption nonces.

Use SecureRandom. If you want to be strict about which algorithm gets picked, use getInstanceStrong().

import java.security.SecureRandom;
import java.util.Base64;

public class Tokens {

    private static final SecureRandom RNG = SecureRandom.getInstanceStrong();

    public static String newToken() {
        byte[] bytes = new byte[32];
        RNG.nextBytes(bytes);
        return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
    }
}

The getInstanceStrong() variant can block on some Linux systems while the OS gathers entropy. If you see startup delays on a VM, use the default SecureRandom constructor instead; it is still cryptographically strong on modern JVMs.

8. Configure TLS Explicitly and Restrict Protocols

Default TLS settings change between JDK versions. I don’t rely on defaults. I set a floor of TLS 1.2 and prefer 1.3, disable renegotiation, and pin the cipher suites to modern ones.

import javax.net.ssl.*;
import java.security.SecureRandom;

SSLContext ctx = SSLContext.getInstance("TLSv1.3");
ctx.init(null, null, SecureRandom.getInstanceStrong());

SSLParameters params = new SSLParameters();
params.setProtocols(new String[]{"TLSv1.3", "TLSv1.2"});
params.setCipherSuites(new String[]{
    "TLS_AES_256_GCM_SHA384",
    "TLS_AES_128_GCM_SHA256",
    "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"
});
params.setEndpointIdentificationAlgorithm("HTTPS");

HttpsURLConnection.setDefaultSSLSocketFactory(ctx.getSocketFactory());

That last line, the endpoint identification algorithm, is what actually checks the hostname on the certificate. Without it, a valid certificate for any domain can be presented and Java will accept it. This is how man-in-the-middle attacks work in practice.

When a handshake fails during troubleshooting, the first thing I check is the server’s -Djavax.net.debug=ssl:handshake output. It prints every cipher the client offered and every cipher the server rejected. Nine times out of ten, the problem is a missing CA in the truststore or a mismatch on TLS version.

9. Validate Input, Encode Output, Never Concatenate SQL

Injection bugs come from trusting strings. SQL injection happens when you paste user input into a query. XSS happens when you paste user input into HTML. Deserialization bugs happen when you turn untrusted bytes back into objects.

For SQL, always use parameterized statements. Here is the one rule I tell every junior engineer: if the string "SELECT" appears anywhere near a + sign, stop.

String sql = "SELECT id, email FROM users WHERE email = ?";
try (PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, email);
    try (ResultSet rs = ps.executeQuery()) {
        // ...
    }
}

For XSS, escape on output with a library like OWASP Java Encoder, and set a Content Security Policy header that blocks inline scripts. Do not try to strip <script> tags by hand; encoders exist because the problem is subtler than it looks.

For deserialization, avoid ObjectInputStream on untrusted data. If you must serialize, use Jackson with an explicit allow-list of types.

ObjectMapper mapper = new ObjectMapper()
    .activateDefaultTypingAsProperty(
        BasicPolymorphicTypeValidator.builder()
            .allowIfSubType("com.myapp.dto.")
            .build(),
        ObjectMapper.DefaultTyping.NON_FINAL,
        "@type");

I also add Bean Validation annotations on my DTOs. @Size, @Pattern, @Email, and @NotNull catch the obvious garbage before it reaches business logic.

10. Rotate Secrets, Scan Dependencies, and Test Security Controls

Security is not a one-time setup. Dependencies get CVEs. Secrets get leaked. Configurations drift. The pattern here is to build rotation and scanning into the pipeline rather than treating them as an annual chore.

For dependency scanning, the OWASP Dependency-Check Maven plugin is the least effort. It runs on every build and fails when a critical CVE appears.

<plugin>
  <groupId>org.owasp</groupId>
  <artifactId>dependency-check-maven</artifactId>
  <version>9.0.9</version>
  <executions>
    <execution>
      <goals><goal>check</goal></goals>
    </execution>
  </executions>
  <configuration>
    <failBuildOnCVSS>7</failBuildOnCVSS>
  </configuration>
</plugin>

For secret rotation, I use short-lived credentials issued by the platform. On AWS, that means IAM roles for service accounts instead of long-lived access keys. When a rotation happens, the running service picks up new credentials from the metadata endpoint without a restart. Static secrets in application.properties are a legacy I try to stamp out wherever I find them.

For testing controls, I write a small suite of negative tests. These are tests that assert the system rejects the wrong input, not that it accepts the right one.

@Test
void rejectsTokenWithWrongIssuer() {
    String forged = issueWithIssuer("evil-corp");
    assertThrows(AuthenticationException.class, () -> tokenService.verify(forged));
}

@Test
void rejectsSqlInjectionPayload() {
    String payload = "' OR 1=1 --";
    List<User> result = repo.findByEmail(payload);
    assertThat(result).isEmpty();
}

I also turn on Java Flight Recorder for production services. A JFR recording captures TLS handshake events, JWT parse failures, and exception traces, which is where security problems show up first. When something suspicious happens, I have the evidence already.

Putting all of this together, the picture is simple. Authentication proves who a caller is, with a validated JWT or an OAuth2 token. Authorization decides what they can do, checked close to the operation. Cryptography protects what is stored, with Argon2 for passwords and AES-GCM for data. Keys live in a KeyStore fed by a secrets manager, never in source control. Input is validated, output is encoded, SQL is parameterized. TLS is configured with a floor, not by default. And every one of these habits gets a test, a scanner, and a rotation schedule.

None of it is exotic. None of it requires a security team. It requires attention, and the willingness to write boring code that fails closed. That is the whole trick, and it is one I keep relearning every time I get lazy.


// Keep Reading

Similar Articles

Java's invokedynamic: Supercharge Your Code with Runtime Method Calls
Java

Java's invokedynamic: Supercharge Your Code with Runtime Method Calls

Java's invokedynamic instruction allows method calls to be determined at runtime, enabling dynamic behavior and flexibility. It powers features like lambda expressions and method references, enhances performance for dynamic languages on the JVM, and opens up possibilities for metaprogramming. This powerful tool changes how developers think about method invocation and code adaptability in Java.

Read Article →