public class CustomAuthenticationEntryPoint extends HttpStatusEntryPoint {
@Override
public void commence(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
if (exception instanceof LockedException) {
response.sendError(HttpStatus.LOCKED.value(), "账户已被锁定,请联系管理员!");
} else {
super.commence(request, response, exception);
}
}
}
@Configuration @EnableWebSecurity public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomAuthenticationEntryPoint authenticationEntryPoint;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.exceptionHandling()
.authenticationEntryPoint(authenticationEntryPoint)
.and()
.authorizeRequests()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/user/**").hasAnyRole("ADMIN", "USER")
.anyRequest().authenticated();
}
}
在上述代码中,将自定义的AuthenticationEntryPoint注入到Spring Security的HttpSecurity中,以便在异常出现时进行处理。
通过以上的方法,我们可以对LockedException异常进行处理,并返回自定义的错误信息。