使用Java配置配置自定义AuthenticationFailureHandler

时间:2014-10-16 05:53:59

标签: java spring spring-security

如何使用基于Java的配置在Spring Security中配置自定义AuthenticationFailureHandler?我已经有SecurityConfig类扩展WebSecurityConfigurerAdapter并使用httpBasic()配置HTTP基本身份验证,但我无法弄清楚如何设置AuthenticationFailureHandler

我的真正目标是重定向到外部网址(登录页面),而不是仅针对某些请求返回401响应(对某些网址的GET请求),因此,如果有其他或更好的方法,我可以#39;我想知道!

2 个答案:

答案 0 :(得分:2)

你必须在failureHandler方法中传递它..链看起来像这样:

http.formLogin().failureHandler()

似乎spring提供的类可以帮助您进行简单的重定向:

http://docs.spring.io/autorepo/docs/spring-security/4.0.0.M2/apidocs/org/springframework/security/web/authentication/SimpleUrlAuthenticationFailureHandler.html

希望它有所帮助。

答案 1 :(得分:2)

我使用了freakman关于创建自定义BasicAuthenticationEntryPoint类的建议。这是我的代码,以防其他人需要做类似的事情:

// See https://github.com/spring-projects/spring-security/blob/3.2.x/web/src/main/java/org/springframework/security/web/authentication/www/BasicAuthenticationEntryPoint.java
public class CustomBasicAuthenticationEntryPoint extends BasicAuthenticationEntryPoint {
    private static Logger logger = loggerFactory.getLogger(CustomBasicAuthenticationEntryPoint.class);

    @Value("${crm.integration.sso.login.form.url}")
    private String loginFormUrl;

    /**
     * This method is called when authentication fails.
     */
    @Override
    public void commence(HttpServletRequest request,
            HttpServletResponse response, AuthenticationException authException)
            throws IOException, ServletException {
        String path = request.getRequestURI().substring(request.getContextPath().length());
        logger.info(String.format("CustomBasicAuthenticationEntryPoint.commence() - %s", path));
        if ("GET".equals(request.getMethod().toUpperCase())
                && path.startsWith("/manage")
        ) {
            response.sendRedirect(loginFormUrl);
        } else {
            super.commence(request, response, authException);
        }
    }

}