LoginFailureHandler.java
2.75 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package com.glsx.usedcar.security;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;
import org.springframework.stereotype.Component;
import org.summerframework.security.validatecode.ValidateCodeException;
import org.summerframework.web.util.HttpHelper;
import java.io.IOException;
/**
* @author keymean
*/
@Component
public class LoginFailureHandler extends SimpleUrlAuthenticationFailureHandler {
@Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
AuthenticationException exception) throws IOException, ServletException {
AuthenticationException authenticationException = handleLoginDisableMessage(exception);
if (HttpHelper.isAjaxRequest(request)) {
HttpHelper.setResponseHeaderFailure(request, response);
String message = authenticationException.getMessage();
response.getWriter().write(message);
} else {
String loginPathString = "/login";
super.setDefaultFailureUrl(loginPathString);
super.onAuthenticationFailure(request, response, authenticationException);
}
}
/**
* 处理security框架返回的登录错误信息
*
* @param exception 异常对象
*/
private AuthenticationException handleLoginDisableMessage(AuthenticationException exception) {
if (exception == null) {
return null;
}
if (exception instanceof DisabledException
|| exception instanceof AccountExpiredException
|| exception instanceof CredentialsExpiredException) {
return new DisabledException("您的账户已被禁用,请联系管理员!");
} else if (exception instanceof LockedException) {
return new BadCredentialsException("账户被锁定,请联系管理员!");
} else if (exception instanceof BadCredentialsException) {
return new BadCredentialsException("用户名或密码错误");
} else if (exception instanceof UsernameNotFoundException) {
return new BadCredentialsException("用户名或密码错误");
} else if (exception instanceof ValidateCodeException) {
return new BadCredentialsException(exception.getMessage());
} else {
return new BadCredentialsException("用户名或密码错误");
}
}
}