Authorization
Authorization answers what are you allowed to do?.
Introduction
Authorization answers what are you allowed to do?. After authentication, Spring Security evaluates URL rules and optional method-security expressions before Orders handlers run.
URL rules in authorizeHttpRequests give coarse policy: public catalog reads, authenticated writes, admin-only deletes. Method security (@PreAuthorize, @PostAuthorize) encodes resource-owner checks that URLs cannot express cleanly.
Enable method security with @EnableMethodSecurity on a configuration class — the Security 6 replacement for older @EnableGlobalMethodSecurity.
Defense in depth: gateway rules, URL rules, and method rules should agree that only the order owner or an admin may cancel.
Purpose of this lesson
Apply URL-level and method-level authorization so Orders operations enforce roles and ownership.
Understanding the topic
Coarse matchers + fine SpEL on methods.
- requestMatchers: path and HTTP method constraints in the filter chain.
- hasRole / hasAuthority: role checks (
ROLE_prefix rules matter). - @PreAuthorize: run before the method; ideal for owner checks.
- @PostAuthorize: inspect the return value (use sparingly — work may already be done).
- @EnableMethodSecurity: turns on annotation-based authorization.
Step-by-step explanation
- Define URL rules: permit auth/health, protect
/api/orders/**, restrict admin paths. - Add
@EnableMethodSecurityto security config. - Annotate
OrderService.cancelwith an owner-or-admin SpEL expression. - Test with mock users in different roles and confirm 403 on forbidden cancels.
Informative example
URL rules plus method-level owner check.
// SecurityFilterChain fragment.authorizeHttpRequests(auth -> auth.requestMatchers(HttpMethod.GET, "/api/catalog/**").permitAll().requestMatchers(HttpMethod.POST, "/api/orders/**").authenticated().requestMatchers("/api/admin/**").hasRole("ADMIN").anyRequest().authenticated())@Configuration@EnableMethodSecurityclass MethodSecurityConfig {}@Servicepublic class OrderService {@PreAuthorize("hasRole('ADMIN') or #customerId == authentication.name")public void cancel(long orderId, String customerId) {// load order, verify state, cancel}}
Real-world use
A TechLearningPRO bug once authorized cancel by order id alone. Any logged-in user who guessed ids could cancel others' checkouts. Moving the check into @PreAuthorize bound to the authenticated name (and verifying ownership again in the service) closed the hole without relying on the UI to hide buttons.
Security implications
Broken access control is a top API risk.
- Deny by default; add permits deliberately.
- Admin role assignment must be an audited operation.
- Never authorize solely in the frontend.
Best practices
- URL rules for broad gates; method security for resource ownership.
- Re-check ownership inside the service for critical mutations.
- Write authorization tests with
@WithMockUser/ Security test support.
Common mistakes
- Trusting a client-sent
userIdfield instead of the principal. - Using
hasRole('ROLE_ADMIN')when Spring already expectsADMINwith the ROLE_ prefix convention. - Enabling method security but placing annotations on private methods that proxies never wrap.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionAuthentication vs authorization?+
Answer
2IntermediateQuestionWhen prefer @PreAuthorize over URL matchers?+
Answer
3BeginnerQuestionWhat annotation enables method security on Security 6?+
Answer
@EnableMethodSecurity on a @Configuration class.Hands-on exercise
Lab. Protect DELETE /api/orders/{id} so only ADMIN or the owning customer succeeds. Attempt cancel as another user and expect 403.
Summary
Orders authorization layers URL policy with method SpEL. Next: JWT as the bearer credential many APIs use after login.