User Roles
We'll extend our application from the default user role to multiple roles.
We'll cover the following...
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:
Press + to interact
@Overrideprotected 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:
Press + to interact
@Overrideprotected 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 ...