【问题标题】:Configure a custom AuthenticationFailureHandler using Java configuration使用 Java 配置配置自定义 AuthenticationFailureHandler
【发布时间】:2015-06-22 00:38:07
【问题描述】:

如何使用基于 Java 的配置在 Spring Security 中配置自定义 AuthenticationFailureHandler?我已经有一个SecurityConfig 类,它扩展WebSecurityConfigurerAdapter 并使用httpBasic() 配置HTTP 基本身份验证,但我不知道如何设置AuthenticationFailureHandler

我的真正目标是重定向到外部 URL(登录页面),而不是仅对某些请求返回 401 响应(对某些 URL 的 GET 请求),所以如果有其他或更好的方法可以做到这一点,我想知道!

【问题讨论】:

    标签: java spring spring-security


    【解决方案1】:

    你必须在 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

    希望对你有帮助。

    【讨论】:

    • 感谢怪物,你的回答对 formLogin() 是正确的,所以我给你一个赞成票。不幸的是,我没有提到我实际上是使用 httpBasic() 来使用 HTTP 基本身份验证。真的很抱歉之前没有提到这一点。我会更新我的问题。
    • 之前没试过.. 但看看 http.httpBasic().authenticationEntryPoint(authEntryPoint)。 AuthEntryPoint 示例是 BasicAuthenticationEntryPoint 类 - 它的开始方法返回未经授权的 http 响应。您可以尝试提供您的课程并使用 HttpServletResponse 中的 sendRedirect 方法。
    【解决方案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);
            }
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-16
      • 2016-03-27
      • 2015-08-03
      • 2015-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多