LoginFailureHandler.java 2.75 KB
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("用户名或密码错误");
        }
    }
}