AI Hints
Home›Spring Boot Tutorial›Users and Passwords, Password Encoding and Roles
Spring Boot · Lesson 96 of 120

Roles

What users may do.

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

Logging in tells us who someone is. Roles tell us what they may do. A reader may list books. Only an admin may delete them.

  • Who: logging in
  • What: roles
  • Reader or admin

Roles and authorities

A role is a name, like user, or admin. Spring stores it as an authority, with a ROLE_prefix. Has role admin checks for ROLE_ADMIN. And a user can have several roles.

keyvalue
RoleUSER, ADMIN
Stored asROLE_ADMIN
CheckhasRole("ADMIN")
Manyroles("USER", "ADMIN")

Rules by role

The rules are checked in order, top to bottom. GET slash books is public. DELETE needs the admin role. Everything else needs any logged in user. Run it. Anyone can list books. Sam is logged in, but not an admin, so delete is forbidden, four oh three. And Alex, the admin, can delete.

SecurityConfig.javajava
@Configuration
public class SecurityConfig {

    @Bean
    SecurityFilterChain api(HttpSecurity http) throws Exception {
        http.authorizeHttpRequests(auth -> auth
                .requestMatchers(HttpMethod.GET, "/books").permitAll()
                .requestMatchers(HttpMethod.DELETE, "/books/**").hasRole("ADMIN")
                .anyRequest().authenticated())
            .httpBasic(Customizer.withDefaults()).csrf(csrf -> csrf.disable());
        return http.build();
    }
}
Output
$ curl localhost:8080/books
["Dune","Circe"]
$ curl -i -u sam:reader1 -X DELETE localhost:8080/books/1 | head -1
HTTP/1.1 403
$ curl -u alex:boss123 -X DELETE localhost:8080/books/1
Deleted book 1
Also uses BookController.java
@RestController
public class BookController {

    @GetMapping("/books")
    public List<String> books() { return List.of("Dune", "Circe"); }

    @DeleteMapping("/books/{id}")
    public String delete(@PathVariable int id) { return "Deleted book " + id; }

    @GetMapping("/me")
    public String me(Authentication auth) {
        return "You are " + auth.getName() + ", roles: " + auth.getAuthorities().stream()
            .map(GrantedAuthority::getAuthority).filter(a -> a.startsWith("ROLE_")).toList();
    }
}
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 -i -u sam:reader1 -X DELETE localhost:8080/books/1 | head -1
curl -u alex:boss123 -X DELETE localhost:8080/books/1
Also uses _profile
security

Summary

Roles are stored as ROLE_authorities. Has role checks them, giving four oh three to users without the role. Next, protecting endpoints by role.

Key takeaways
  • roles("ADMIN")
  • hasRole("ADMIN")
  • 403 Forbidden
Next up: Protecting Endpoints by Role — rules for every URL