一.简介
在Spring Security中异常分为两种:
- AuthenticationException 认证异常
- AccessDeniedException 权限异常 我们先给大家演示下如何自定义异常处理器,然后再结合源码帮助大家进行分析
二.创建项目
如何创建一个SpringSecurity项目,前面文章已经有说明了,这里就不重复写了。
三.自定义异常处理器
3.1配置SecurityConfig
这里主要是authenticationEntryPoint和accessDeniedHandler配置,代码如下:
@Bean
public SecurityFilterChain config(HttpSecurity http) throws Exception {
http.authorizeHttpRequests()
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login.html")
.loginProcessingUrl("/login")
.permitAll()
.and()
.cors()
.configurationSource(corsConfigurationSource())
.and()
.exceptionHandling()
.authenticationEntryPoint(new AuthenticationEntryPoint() {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
Map<String, Object> result = new HashMap<>();
result.put("code", -1);
result.put("msg", "authenticationEntryPoint");
result.put("data", authException.getMessage());
System.out.println("调用次数");
writeResp(result, response);
}
}).accessDeniedHandler(new AccessDeniedHandler() {
@Override
public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
Map<String, Object> result = new HashMap<>();
result.put("code", -1);
result.put("msg", "accessDeniedHandler");
result.put("data", accessDeniedException.getMessage());
writeResp(re