Spring Security 5: Restric Access

Create supporting controller code and view pages

  • Add a hyperlink in home page and refer to /leaders
  • Create a controller with @GetMapping("/leaders") and return to leaders.jsp
  • Create a page for leaders
  • Repeat the job for different roles, nothing special

    Update user roles

    DemoSecurityConfig.java:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
    // add our users for in memory authentication
    UserBuilder users = User.withDefaultPasswordEncoder();

    auth.inMemoryAuthentication()
    .withUser(users.username("john").password("test123").roles("EMPLOYEE"))
    .withUser(users.username("mary").password("test123").roles("EMPLOYEE","MANAGER"))
    .withUser(users.username("susan").password("test123").roles("EMPLOYEE","ADMIN"));
    }

Restrict Access based on Roles

General syntax:

1
.antMatchers(<< add path to match on >>).hasRole(<< authorized role >>)

or

1
2
// Any role in the list, comma-delimited list. E.g. "ADMIN","DEVELOPER","VIP","PLATINUM"
.antMatchers(<< add path to match on >>).hasAnyRole(<< authorized role >>)

DemoSecurityConfig.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@Override
protected void configure(HttpSecurity http) throws Exception {

http.authorizeRequests()
.antMatchers("/").hasRole("EMPLOYEE")
.antMatchers("/leaders/**").hasRole("MANAGER")
.antMatchers("/admins/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/showMyLoginPage")
.loginProcessingUrl("/authenticateTheUser")
.permitAll()
.and()
.logout()
.permitAll();
}

In this way, if a user tries to access in a page which he is not authorized to, he will be denied by “HTTP Status 403 - Forbidden”.