1、UserNotFoundExceptions未抛出
@Bean
public DaoAuthenticationProvider daoAuthenticationProvider() {
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setUserDetailsService(memberDetailsService);
daoAuthenticationProvider.setHideUserNotFoundExceptions(false);
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder);
return daoAuthenticationProvider;
}
@Override
public void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(daoAuthenticationProvider());
}
注意:
@Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthenticationProvider()); }
不能修改成:
@Override public void configure(AuthenticationManagerBuilder auth) throws Exception { auth.authenticationProvider(daoAuthenticationProvider()).userDetailsService(userDetailsService()).passwordEncoder(passwordEncoder); }
2、AccessDeniedHandler异常自定义拦截
.exceptionHandling().accessDeniedHandler(authenticationAccessDeniedHandler)
3、其余异常自定义拦截,AuthenticationException 自定义处理
public class CannaAuthenticationFailureHandler implements
AuthenticationFailureHandler {
public CannaAuthenticationFailureHandler() {
}
/**
* Performs the redirect or forward to the {@code defaultFailureUrl} if set, otherwise
* returns a 401 error code.
* <p>
* If redirecting or forwarding, {@code saveException} will be called to cache the
* exception for use in the target view.
*/
public void onAuthenticationFailure(HttpServletRequest request,
HttpServletResponse response, AuthenticationException authenticationException)
throws IOException, ServletException {
response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
SecurityErrorType securityErrorType = null;
if (authenticationException instanceof UsernameNotFoundException || authenticationException instanceof BadCredentialsException) {
securityErrorType = SecurityErrorType.USERNAME_PASSWORD_ERROR;
} else if (authenticationException instanceof DisabledException) {
securityErrorType = SecurityErrorType.USER_DISABLE;
} else if (authenticationException instanceof LockedException) {
securityErrorType = SecurityErrorType.ACCOUNT_LOCK;
} else if (authenticationException instanceof AccountExpiredException) {
securityErrorType = SecurityErrorType.ACCOUNT_EXPIRED;
} else if (authenticationException instanceof CredentialsExpiredException) {
securityErrorType = SecurityErrorType.CREDENTIALS_EXPIRED;
} else {
securityErrorType = SecurityErrorType.CHECK_AUTH_FAIL;
}
ErrorInfo errorJson = securityErrorType.toErrorInfo();
ResponseUtils.writeResult(response, HttpStatus.INTERNAL_SERVER_ERROR, errorJson);
}
}
// 类中重新设置错误执行类
public UsernamePasswordAuthenticationFilter() {
// do nothing
super.setAuthenticationFailureHandler(new CannaAuthenticationFailureHandler());
}