在Spring Security中,当用户尝试访问其没有权限的资源时,系统会返回一个HTTP状态码为403的错误页面。可以自定义403页面来提供更友好的用户体验。
详细步骤如下:
-
创建自定义403页面
:创建一个自定义的403页面,例如forbidden.html。 -
配置访问规则
:配置Spring Security,指定访问受限资源时跳转到自定义的403页面。
代码如下:
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasRole("USER")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.exceptionHandling()
.accessDeniedPage("/403");
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN")
.and()
.withUser("user")
.password(passwordEncoder().encode("user123"))
.roles("USER");
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
在上面的代码中,通过 configure() 方法配置了自定义403页面。指定了访问受限资源时跳转到"/403"页面。在 configure() 方法中,配置了两个用户信息,一个是具有"ADMIN"角色的"admin"用户,另一个是具有"USER"角色的"user"用户。
通过这样的配置,当用户尝试访问其没有权限的资源时,系统会返回一个HTTP状态码为403,并跳转到自定义的403页面提供友好的提示信息。这种方式可以实现自定义403页面的需求。