springsecurity自定义403
时间: 2023-06-30 10:18:37 浏览: 112
要自定义Spring Security中的403错误页面,可以按照以下步骤进行操作:
1. 创建一个403.html页面,用于显示自定义错误信息。
2. 创建一个自定义的AccessDeniedHandler类,用于处理访问被拒绝的情况。
3. 在Spring Security配置文件中配置AccessDeniedHandler,指定使用自定义的AccessDeniedHandler处理访问被拒绝的情况。
以下是一个简单的示例代码:
1. 创建403.html页面
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Access Denied</title>
</head>
<body>
<h1>Access Denied</h1>
<p>You are not authorized to access this resource.</p>
</body>
</html>
```
2. 创建自定义的AccessDeniedHandler类
```
@Component
public class CustomAccessDeniedHandler implements AccessDeniedHandler {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException e) throws IOException, ServletException {
response.sendRedirect("/403.html");
}
}
```
3. 在Spring Security配置文件中配置AccessDeniedHandler
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAccessDeniedHandler accessDeniedHandler;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.anyRequest().authenticated()
.and()
.formLogin()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
}
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("password").roles("USER")
.and()
.withUser("admin").password("password").roles("USER", "ADMIN");
}
}
```
以上代码中,CustomAccessDeniedHandler类是自定义的AccessDeniedHandler实现类,它在处理访问被拒绝的情况时,通过重定向到403.html页面来显示自定义错误信息。在SecurityConfig配置类中,通过exceptionHandling().accessDeniedHandler(accessDeniedHandler)方法来指定使用自定义的AccessDeniedHandler处理访问被拒绝的情况。
阅读全文