Skip to content
javahacks.dev
Security

OWASP Top Ten for Java Developers With Code Examples

The OWASP Top Ten web risks mapped to Java and Spring: what each one looks like in code, a fix for each and where to read the full guidance.

7 min read
Summarize in AI
Flat illustration of a security filter chain guarding a request, with the Spring Security and OpenJDK logos.

The OWASP Top Ten is the most widely used list of web application risks, and the useful way to read it as a Java developer is as a checklist of code patterns. This post uses the 2021 edition, the version most tools and audits refer to; check the OWASP site for newer editions, which reorder and rename some categories. Each entry has a Java shape and a fix. The habits underneath are in Java security basics.

A01 Broken access control

A user changes /orders/42 to /orders/43 and sees someone else's order. The code loads by id and never checks the owner.

java
Order order = orders.findById(id).orElseThrow();
if (!order.customerId().equals(currentUser.id())) {
    throw new AccessDeniedException("Not your order");
}

Enforce on the server for every request; use method security (@PreAuthorize) and write a test that logs in as user A and requests user B's resource.

A02 Cryptographic failures

Sensitive data sent over HTTP, passwords hashed with MD5, keys in source code. Use TLS everywhere, BCryptPasswordEncoder or Argon2 for passwords, authenticated encryption (AES-GCM) with keys from a key store, and never invent your own scheme. Trust problems are handled in PKIX failures, not by disabling checks.

A03 Injection

SQL, JPQL, OS commands, LDAP, expression language. The fix is separating data from code: parameterized queries, argument arrays for processes, allow-lists for identifiers. The Struts history in using OGNL safely shows expression injection.

A04 Insecure design

A flaw in the design, not the code: a password reset that reveals whether an email exists, unlimited login attempts, a business rule that can be abused by repeating a request. The fix is earlier: threat modeling, rate limits and tests for abuse cases, such as repeated coupons.

A05 Security misconfiguration

Default credentials, verbose errors, exposed Actuator endpoints, directory listing, debug mode in production. In Spring Boot, expose only health and info over HTTP by default, set server.error.include-stacktrace=never, and review CORS (CORS configuration). Run configuration checks in CI.

A06 Vulnerable and outdated components

Known-vulnerable libraries in the dependency tree. Scan with Dependency-Check, Dependabot or a commercial tool, fail the build on high severity findings and update regularly. Know your transitive dependencies (Maven mediation shows what you actually get).

A07 Identification and authentication failures

Weak passwords allowed, no lockout, session ids in URLs, sessions that survive logout. Use a framework (Spring Security), enforce password length, hash with a slow algorithm, rotate the session id on login and support multi-factor authentication where the data justifies it. Messages from failures are covered in 401 Unauthorized.

A08 Software and data integrity failures

Unsigned updates, insecure deserialization, a CI pipeline that pulls untrusted code. Avoid Java native deserialization of untrusted input, verify artifact checksums and signatures, pin dependency versions and protect the build system.

A09 Security logging and monitoring failures

Attacks that nobody notices. Log logins, failures and access denials with enough context, protect logs from tampering and injection, and alert on patterns. A log that nobody reads, or that holds passwords, is a liability.

A10 Server-side request forgery

The server fetches a URL supplied by the user and is tricked into reaching internal services or cloud metadata endpoints.

java
URI uri = URI.create(userUrl);
if (!uri.getScheme().equals("https") || !ALLOWED_HOSTS.contains(uri.getHost())) {
    throw new IllegalArgumentException("Host not allowed");
}

Allow-list hosts, resolve and reject private address ranges after DNS resolution, disable redirects or revalidate them, and keep outbound network access minimal.

How to use the list

Treat it as a review prompt. For each category, find where your application does the relevant thing and check the control. Automated tools catch some (injection patterns, vulnerable libraries); design and access control flaws need a human and tests.

Several controls in one Spring Boot service

The categories overlap in practice, so it helps to see them together. This configuration closes the common holes of A01, A02, A05 and A07 for a Spring Boot 3 or 4 API:

java
@Configuration
@EnableMethodSecurity
class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        return http
            .authorizeHttpRequests(auth -> auth
                .requestMatchers("/actuator/health").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .oauth2ResourceServer(oauth -> oauth.jwt(Customizer.withDefaults()))
            .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
            .headers(h -> h
                .contentTypeOptions(Customizer.withDefaults())
                .httpStrictTransportSecurity(hsts -> hsts.includeSubDomains(true).maxAgeInSeconds(31536000)))
            .build();
    }

    @Bean
    PasswordEncoder passwordEncoder() {
        return PasswordEncoderFactories.createDelegatingPasswordEncoder();
    }
}

anyRequest().authenticated() is the line that matters most. It makes the default deny, so a new endpoint is protected until someone decides otherwise. The delegating encoder stores the algorithm name in the hash, which lets you change algorithms later without a migration flag day.

Authentication is only half of A01, and the other half is checking ownership. Put it on the method, where it cannot be forgotten by a new controller:

java
@Service
class OrderService {

    @PostAuthorize("returnObject.customerId() == authentication.name")
    Order find(long id) {
        return orders.findById(id).orElseThrow(OrderNotFound::new);
    }
}

The test that proves A01

Access control bugs survive because nobody wrote the test that logs in as the wrong person:

java
@SpringBootTest
@AutoConfigureMockMvc
class OrderAccessTest {

    @Autowired MockMvc mvc;

    @Test
    @WithMockUser(username = "alice")
    void aliceCannotReadBobsOrder() throws Exception {
        mvc.perform(get("/orders/{id}", BOBS_ORDER_ID))
           .andExpect(status().isForbidden());
    }
}

Keep one such test per resource type. When a new endpoint arrives, copying the test is cheaper than the incident.

Injection and logging, side by side

A03 and A09 meet in one place: the log line. Parameterized queries stop the first, and a sanitized message stops log forging, where a user puts a newline in a field and writes a fake entry:

java
@Query("select o from Order o where o.customerId = :customerId and o.status = :status")
List<Order> search(@Param("customerId") String customerId, @Param("status") Status status);

log.info("login failed for user={}", username.replaceAll("[\\r\\n]", "_"));

The query binds both values as parameters, so there is nothing for an attacker to terminate. The log call uses a placeholder and strips line breaks from the one field a caller controls. If you use a structured JSON log encoder, the encoder escapes the newline for you, which is one more argument for structured logs.

Where to start on an existing service

Run the dependency scan first, because it is cheap and finds A06 without reading any code. Then grep for string-built SQL, then list every endpoint and mark which of them check the owner of the resource. Those three passes usually find more than a week of general review. After that, add the checks to the pipeline so they run on every merge: the scan as a build step that fails on high severity, the access test as part of the normal suite, and a linter rule that flags string concatenation inside anything passed to createQuery or JdbcTemplate. A control that depends on someone remembering it fades within a quarter, and a control in the build does not.

Assigning the list to people

A checklist nobody owns is not a control. After you have read the ten categories against your service, assign each one to a role and a place in the delivery process. Access control and insecure design belong with the developers who write the endpoints and the people who review their designs, so they need a test and a review question each. Cryptographic failures, misconfiguration and logging belong with the platform or operations team, because the fix is a setting or a template that every service inherits. Vulnerable components belong to the pipeline, and the fix is a failing build with a named owner for the exceptions.

Write down the exceptions as well. A team that accepts a finding should record who accepted it, why, and when it will be looked at again, because an unrecorded exception is indistinguishable from an oversight six months later. Review the list when the architecture changes, such as a new public endpoint or a new third-party integration, and not on a calendar, since the risks move with the design. A short document of this kind, kept in the repository next to the service, does more for security than a longer policy that lives in a wiki.

Where the list stops

The Top Ten is an awareness document, not a standard. The OWASP Application Security Verification Standard (ASVS) is the detailed checklist for assessments. The OWASP Top Ten project page and the OWASP Cheat Sheet Series are the primary sources.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.