有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

spring使用Java配置配置自定义AuthenticationFailureHandler

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

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


共 (2) 个答案

  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);
            }
        }
    
    }