Skip to content
Tutorials Center
My learning

Topics

Lesson 39 of 39 ยท Projects and Practice

Practice: Reviewing Spring Security Code

Sharpen your eye with Spring Security review exercises: rule ordering, path matching bugs, missing ownership checks, weak tokens and unsafe CORS, each with a runnable demonstration.

Knowing the API is one skill; spotting what is wrong in someone else's configuration is another, and it is what security reviews are made of. This lesson is a set of exercises. Each shows a snippet with a flaw, asks you to find it, then explains the fix. Two flaws are demonstrated with runnable Java stand-ins so you can see the failure, not just read about it.

Spring Security itself cannot run on this site; the snippets are read-only and the demos model the underlying mistakes in plain Java.

How to review

Walk every snippet with the same questions:

  1. Who can reach this? (anonymous, any user, one role)
  2. What does it trust that comes from the client? (path, header, token claim, id)
  3. What happens when the rule does not match? (default deny or default allow)
  4. What leaks on failure? (messages, timing, existence)

Four review questions

Who? Anonymous, user, admin
Trusted input? Path, id, claim, header
No match? Deny by default
What leaks? Errors and existence

Ask them for every endpoint

1 / 2

Exercise 1: rule order

Java
http.authorizeHttpRequests(auth -> auth
    .requestMatchers("/**").authenticated()
    .requestMatchers("/admin/**").hasRole("ADMIN")
    .requestMatchers("/health").permitAll());

Find the flaw. Rules are checked top to bottom and the first match wins. /** matches everything, so the admin rule and the public health rule are never reached: any signed-in user is now an admin, and the health check requires a login. Spring Security 6 rejects some unreachable orderings at startup, but not every mistake is caught.

Fix. Put the most specific rules first and the catch-all last:

Java
.requestMatchers("/health").permitAll()
.requestMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()

Revisit request matchers and rules if the matching order is unclear.

Exercise 2: hand-written path checks

Java
@Component
class AdminFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest req, HttpServletResponse res, FilterChain chain)
            throws IOException, ServletException {
        String path = req.getRequestURI();
        if (path.startsWith("/admin") && !isAdmin(req)) {
            res.sendError(403);
            return;
        }
        chain.doFilter(req, res);
    }
}

Find the flaw. Hand-rolled string checks disagree with how the framework maps URLs. Variants such as /admin/../admin, encoded dots, doubled slashes or ;jsessionid= path parameters may reach the controller while failing a naive startsWith. The demo shows the gap between the raw string and the normalized path.

Java Naive path check vs normalized path (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The traversal path /public/../admin/users is invisible to the naive check, which is why the filter would let it through to a handler that serves the admin area. Notice two more lessons in the table: /administrator fools a loose startsWith, and case matters (/Admin/users may or may not map to the same handler, depending on server configuration).

Fix. Do not write your own URL authorization. Use requestMatchers (it matches the same normalized path Spring MVC uses), and back it with @PreAuthorize on the controller methods.

Exercise 3: the missing ownership check

Java
@GetMapping("/invoices/{id}")
@PreAuthorize("hasRole('USER')")
Invoice get(@PathVariable long id) {
    return invoices.findById(id).orElseThrow();
}

Find the flaw. Any user may read any invoice by changing the id (an insecure direct object reference, often called IDOR or broken object-level authorization). The role check says who, not whose data.

Java IDOR: before and after (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Fix. Put the owner into the query, or check it with a method-security expression:

Java
@PreAuthorize("@invoiceAccess.isOwner(#id, authentication.name)")

Return 404 for records the caller may not see.

Exercise 4: tokens and claims

Java
JwtDecoder decoder = NimbusJwtDecoder.withSecretKey(new SecretKeySpec("secret".getBytes(), "HmacSHA256")).build();

Find the flaws. A six-character shared secret can be brute-forced offline from one captured token; the same secret on every service means any service can mint tokens; there is no audience or issuer validation. Also, never authorize from a claim the client can influence unless the signature covers it. Fix with long random keys from a vault, asymmetric signing where only the identity provider holds the private key, and validators for issuer and audience; see JWT signing.

Exercise 5: CORS and CSRF shortcuts

Java
http.csrf(csrf -> csrf.disable())
    .cors(cors -> cors.configurationSource(req -> {
        CorsConfiguration c = new CorsConfiguration();
        c.addAllowedOriginPattern("*");
        c.setAllowCredentials(true);
        c.addAllowedMethod("*");
        c.addAllowedHeader("*");
        return c;
    }));

Find the flaw. CSRF is disabled while the app may still use cookie sessions, and the CORS policy lets any origin make credentialed requests and read the answers. Together this hands every website your logged-in users visit a way to act as them. Fix: keep CSRF on for cookie-based apps, list exact origins, and only allow the methods and headers you use; see CORS configuration and CSRF protection.

Your own review checklist

Write down, for any project you inherit: every permitAll(), every csrf().disable(), every place a client-supplied id reaches the database, every secret in configuration, every actuator exposure, and every log line that includes a token. Fixing those six classes of issue removes most of the real-world Spring Security vulnerabilities.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In requestMatchers rules, what decides which rule applies?

    Order matters, so list specific rules before general ones and end with anyRequest().
  2. 2. What is an insecure direct object reference?

    A role check alone does not prove the record belongs to the caller.
  3. 3. Why is a hand-written startsWith('/admin') check unsafe?

    Traversal segments, encodings and path parameters can make the raw string differ from the path that gets handled.
  4. 4. Which CORS setting is dangerous with cookies?

    Any website could then call your API as the logged-in user and read the response.

Summary

  • Review with four questions: who, which inputs are trusted, what happens on no match, what leaks.
  • Order rules specific-first and finish with default deny.
  • Use the framework's matchers, never raw string checks, and enforce ownership in the data access.
  • Use strong, separate keys and validate issuer and audience.
  • Keep CSRF on for cookie apps and keep CORS origins explicit.

Next: back to the Spring Security track for the full lesson list.