Skip to the page

Spring Security · mid

Object-level authorization, CORS and reviewing a config

Checking the role is not enough: check that the user owns the object. CORS belongs inside the security chain. Rules match top to bottom.

The notes

What you must know

  • IDOR (broken object-level authorisation): the check is only "is a customer", not "owns this account". Sequential ids make it easy to walk through all accounts.
  • Fix in the data access: accountRepository.findByIdAndOwnerId(accountId, currentUserId); empty gives 404. Or @PreAuthorize("@accountAccess.canRead(#accountId, authentication)").
  • 404 does not confirm that the account exists. Staff need a separate permission with an audit log. Test: user B gets 404 for user A's resource on every endpoint with an id. Random ids do not replace the check.
  • CORS is enforced only by browsers. A JSON POST triggers a preflight OPTIONS request. The security chain can answer it with 401 before the CORS filter runs.
  • Configure CORS inside Spring Security: http.cors(Customizer.withDefaults()) and a CorsConfigurationSource bean with exact origins, methods and headers.
  • Browsers refuse * with credentials, and Spring rejects allowedOrigins("*") with allowCredentials(true).
  • CSRF depends on how the browser authenticates. With cookies keep CSRF on. Turning it off with form login and open CORS lets any website send authenticated requests.
  • Rules are checked top to bottom and the first match wins. /api/** before /api/admin/** lets any user act as admin. End with denyAll() or authenticated(), never anyRequest().permitAll(). Do not leave /actuator/** open. Tests: MockMvc with @WithMockUser(roles = "USER") gives 403 on admin URLs.

The red pen

Common traps: mistake → fix

  • Mistake: Role checks are enough to protect data

    Fix: they do not check ownership.

  • Mistake: CORS errors mean the server is down

    Fix: the preflight was rejected by the security chain.

  • Mistake: Order of requestMatchers does not matter

    Fix: the first match wins.

Easy to hard

Questions interviewers ask, easy to hard

  1. A tester changes the account number in the URL and sees another customer's data. What is wrong?
  2. Every POST from React fails with a CORS error after adding Spring Security. Why?
  3. Review this security config. What is wrong?
  4. Which tests do you write for object-level authorisation?

Explain it out loud

Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.

Practise by voice

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview