Search⌘ K

User Roles

Explore how to secure Spring Boot applications by managing user roles with URL-based and annotation-driven authorization. Understand role-specific access control using Spring Security, customize error handling for unauthorized actions, and configure method-level security with @Secured annotations in Thymeleaf-based projects.

URL based authorization

We have used the single role USER so far, but most applications have multiple roles for their users. This allows only certain operations (like deleting e a user) for certain roles (like administrators).

As an example of how this works, we will create a second hardcoded user admin which has the USER and ADMIN roles:

Java
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user")
.password(passwordEncoder.encode("verysecure"))
.roles("USER")
.and()
.withUser("admin")
.password(passwordEncoder.encode("evenmoresecure"))
.roles("USER", "ADMIN");
}

We can now override the configure(HttpSecurity http) method to determine which user role is allowed to access which part of the application:

Java
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests() // <.>
.antMatchers("/users/create").hasRole("ADMIN") // <.>
.antMatchers("/users/*/delete").hasRole("ADMIN") // <.>
.antMatchers(HttpMethod.GET, "/users/*").hasRole("USER") // <.>
.antMatchers(HttpMethod.POST, "/users/*").hasRole("ADMIN") // <.>
.and()
.formLogin().permitAll() // <.>
.and()
.logout().permitAll(); // <.>
}
  • We want requests to be authorized.

  • Only a user with an ADMIN role can access /users/create. This is valid for any HTTP method (so GET, POST, etc.)

  • Only a user with an ADMIN role can access a URL that matches with /users/*/delete. The * means any character except /.

  • We can also secure a path with a ...