AI Hints
Home›Spring Boot Tutorial›Protecting Endpoints by Role, Method Security and Practice: A Secured API
Spring Boot · Lesson 97 of 120

Protecting Endpoints by Role

Rules for every URL.

⏱ 2 min read▶ Video at 2:08:25🎓 Free
Watch this lesson in the Spring Boot courseWatch on YouTube ↗Full Spring Boot course

As an API grows, it gets public parts, user parts, and admin parts. Path patterns let one rule cover a whole group of URLs.

  • Public parts
  • User parts
  • Admin parts

Matching and rules

Two stars match everything below a path, like slash admin slash two stars. Has role needs one role. Has any role accepts any of several. Permit all lets everyone in. And deny all blocks everyone, which is a safe default for anything you forgot.

PieceMeaning
/admin/**everything under /admin
hasRole("ADMIN")needs ADMIN
hasAnyRole("USER", "ADMIN")either role
permitAll()everyone
denyAll()no one

A rule per area

Books are public. Everything under admin needs the admin role. Orders need user, or admin. And any other URL is denied. Run it. Anyone sees the books. Sam sees Sam's own orders. Sam can't see the admin report, so it's four oh three. Alex can. And an unknown URL is denied, even for Alex.

SecurityConfig.javajava
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers("/books/**").permitAll()
                .requestMatchers("/admin/**").hasRole("ADMIN")
                .requestMatchers("/orders/**").hasAnyRole("USER", "ADMIN")
                .anyRequest().denyAll())
            .httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }
}
Output
$ curl localhost:8080/books
Public: the book list
$ curl -u sam:reader1 localhost:8080/orders
Orders for sam
$ curl -i -u sam:reader1 localhost:8080/admin/report | head -1
HTTP/1.1 403
$ curl -u alex:boss123 localhost:8080/admin/report
Admin: sales report
$ curl -i -u alex:boss123 localhost:8080/secret | head -1
HTTP/1.1 403
Also uses ShopController.java
@RestController
public class ShopController {

    @GetMapping("/books")
    public String books() { return "Public: the book list"; }

    @GetMapping("/orders")
    public String orders(Authentication auth) { return "Orders for " + auth.getName(); }

    @GetMapping("/admin/report")
    public String report() { return "Admin: sales report"; }
}
Also uses UserConfig.java
@Configuration
public class UserConfig {
    @Bean
    UserDetailsService users() {
        return new InMemoryUserDetailsManager(
            User.withUsername("sam").password("{noop}reader1").roles("USER").build(),
            User.withUsername("alex").password("{noop}boss123").roles("USER", "ADMIN").build());
    }
}
Also uses _curl.sh
curl localhost:8080/books
curl -u sam:reader1 localhost:8080/orders
curl -i -u sam:reader1 localhost:8080/admin/report | head -1
curl -u alex:boss123 localhost:8080/admin/report
curl -i -u alex:boss123 localhost:8080/secret | head -1
Also uses _profile
security

Summary

Path patterns, with has role, has any role, permit all, and deny all, protect whole areas of your API. Next, method security.

Key takeaways
  • /admin/**
  • hasAnyRole
  • denyAll() by default
Next up: Method Security — rules on methods