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

    Authorization

    Authorization answers what are you allowed to do?.

    Course progress0%
    Focus
    3 guided sections
    Practice signal
    Examples included
    Career prep
    Foundation builder

    Introduction

    Authorization answers what are you allowed to do?. Spring Security supports URL-level rules and method-level rules with SpEL expressions.

    Informative example

    ts
    // URL-based
    .authorizeHttpRequests(a -> a
    .requestMatchers(HttpMethod.GET, "/api/v1/products/**").permitAll()
    .requestMatchers(HttpMethod.POST, "/api/v1/products/**").hasRole("ADMIN")
    .anyRequest().authenticated())
    // Method-based
    @PreAuthorize("hasRole('ADMIN') or #userId == authentication.principal.id")
    public UserDto get(Long userId) { ... }
    @PostAuthorize("returnObject.ownerId == authentication.principal.id")
    public OrderDto find(Long id) { ... }

    Best practices

    • URL rules for coarse policies; @PreAuthorize for resource-owner checks.
    • Enable with @EnableMethodSecurity on a @Configuration.
    • Test authorisation with @WithMockUser.
    Ready to mark this lesson complete?Track your journey across the entire course.