Spring Security 6: Customize Access Denied Page

Since we don’t want the default access denied page, we can create a customized one.

Update DemoSecurityConfig

DemoSecurityConfig.java:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@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()
// new added
.and()
// "/access-denied" needs a new controller
.exceptionHandling().accessDeniedPage("/access-denied");
}

Update LoginController

LoginController.java:

1
2
3
4
@GetMapping("/access-denied")
public String accessDenied() {
return "access-denied";
}

Create page /access-denied

Skip