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.
Explain it out loud
Explain it out loud to an AI interviewer that follows up, and see where your answer is thin.
Practise by voiceThe 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 aCorsConfigurationSourcebean with exact origins, methods and headers. - Browsers refuse
*with credentials, and Spring rejectsallowedOrigins("*")withallowCredentials(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 withdenyAll()orauthenticated(), neveranyRequest().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
- A tester changes the account number in the URL and sees another customer's data. What is wrong?
- Every POST from React fails with a CORS error after adding Spring Security. Why?
- Review this security config. What is wrong?
- 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 voiceYour first interview is free
Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.