Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 40

    Authorization

    Authorization answers what are you allowed to do?.

    Course progress0%
    Focus
    12 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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

    1. Define URL rules: permit auth/health, protect /api/orders/**, restrict admin paths.
    2. Add @EnableMethodSecurity to security config.
    3. Annotate OrderService.cancel with an owner-or-admin SpEL expression.
    4. Test with mock users in different roles and confirm 403 on forbidden cancels.

    Informative example

    URL rules plus method-level owner check.

    java
    // 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
    @EnableMethodSecurity
    class MethodSecurityConfig {}
    @Service
    public 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 userId field instead of the principal.
    • Using hasRole('ROLE_ADMIN') when Spring already expects ADMIN with 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.

    3 questions
    1BeginnerQuestionAuthentication vs authorization?+

    Answer

    Authentication proves identity; authorization decides whether that identity may perform an action.
    2IntermediateQuestionWhen prefer @PreAuthorize over URL matchers?+

    Answer

    When the decision depends on method arguments or loaded resource ownership that paths alone cannot express.
    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.

    Ready to mark this lesson complete?Track your journey across the entire course.