SpringBoot+ES项目:8. 业务开发 - 验证失败逻辑

1. 主要原理
实现 SimpleUrlAuthenticationFailureHandler 注入WebSecurityConfig

2. 验证失败现状

跳转至404页面
SpringBoot+ES项目:8. 业务开发 - 验证失败逻辑_第1张图片

3. 实现一个SimpleUrlAuthenticationFailureHandler类

package com.xunwu.security;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录验证失败处理器
 * Created by 瓦力.
 */
public class LoginAuthFailHandler extends SimpleUrlAuthenticationFailureHandler {
    private final LoginUrlEntryPoint urlEntryPoint;

    public LoginAuthFailHandler(LoginUrlEntryPoint urlEntryPoint) {
        this.urlEntryPoint = urlEntryPoint;
    }

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response,
                                        AuthenticationException exception) throws IOException, ServletException {
        String targetUrl =
                this.urlEntryPoint.determineUrlToUseForThisRequest(request, response, exception);

        targetUrl += "?" + exception.getMessage();
        super.setDefaultFailureUrl(targetUrl);
        super.onAuthenticationFailure(request, response, exception);
    }
}

SpringBoot+ES项目:8. 业务开发 - 验证失败逻辑_第2张图片

4. 注入WebSecurityConfig

SpringBoot+ES项目:8. 业务开发 - 验证失败逻辑_第3张图片
在登录后配置登陆失败handler
SpringBoot+ES项目:8. 业务开发 - 验证失败逻辑_第4张图片

5. 效果
SpringBoot+ES项目:8. 业务开发 - 验证失败逻辑_第5张图片

你可能感兴趣的:(Spring)