具有基本身份验证的 Spring Security 重定向到/error 以获取无效凭据

标签 spring security authentication basic-authentication credentials

我有一个使用基本身份验证的 Spring Security 运行的 Spring Boot 应用程序。
当提供正确的基本身份验证凭据时,一切都很好,但是对于不正确的身份验证凭据,spring 会提供 HttpRequestMethodNotSupportedException: Request method 'POST' not supported异常(exception)。

根据日志,spring 已经识别出身份验证失败,但结果不是这样。
2015-08-12 09:33:10.922 INFO 16988 --- [nio-8080-exec-4] o.s.b.a.audit.listener.AuditListener : AuditEvent [timestamp=Wed Aug 12 09:33:10 AEST 2015, principal=anonymousUser, type=AUTHORIZATION_FAILURE, data={type=org.springframework.security.access.AccessDeniedException, message=Access is denied}] 2015-08-12 09:33:10.927 TRACE 16988 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Bound request context to thread: FirewalledRequest[ org.apache.catalina.core.ApplicationHttpRequest@483e1fc6] 2015-08-12 09:33:10.927 DEBUG 16988 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : DispatcherServlet with name 'dispatcherServlet' processing POST request for [/myapplication/error] 2015-08-12 09:33:10.927 TRACE 16988 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Testing handler map [org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@331bb032] in DispatcherServlet with name 'dispatcherServlet' 2015-08-12 09:33:10.927 TRACE 16988 --- [nio-8080-exec-4] o.s.w.s.handler.SimpleUrlHandlerMapping : No handler mapping found for [/error] 2015-08-12 09:33:10.927 TRACE 16988 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Testing handler map [org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping@69e79b9b] in DispatcherServlet with name 'dispatcherServlet' 2015-08-12 09:33:10.927 TRACE 16988 --- [nio-8080-exec-4] o.s.web.servlet.DispatcherServlet : Testing handler map [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping@27cc0354] in DispatcherServlet with name 'dispatcherServlet' 2015-08-12 09:33:10.927 DEBUG 16988 --- [nio-8080-exec-4] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /error 2015-08-12 09:33:10.928 DEBUG 16988 --- [nio-8080-exec-4] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'POST' not supported
通过上面的日志&调试spring源码后,我发现当识别出凭证不正确时,spring会创建一个BadCredentials异常然后尝试重定向到“/error”,这个重定向是导致HttpMethodNotAllowed异常的原因。(我的应用程序没有/error 端点)。

我试图通过配置以下内容告诉spring不要使用/error,

`公共(public)类 ServerCustomization 扩展 ServerProperties {

@Override
public void customize(ConfigurableEmbeddedServletContainer container) {

    super.customize(container);
    container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, null));

}`

这将使 spring 停止吐出 HttpMethodnotallowed 异常并使其出现 401(未授权),但是我的异常处理程序没有捕获我的这个异常(使用 @ControllerAdvice 配置)。

我还尝试配置一个自定义身份验证入口点,如下所示,没有任何运气。
@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

AlwaysSendUnauthorized401AuthenticationEntryPoint alwaysSendUnauthorized401AuthenticationEntryPoint = 
        new AlwaysSendUnauthorized401AuthenticationEntryPoint();


@Override
protected void configure(HttpSecurity http) throws Exception {
    http.headers().httpStrictTransportSecurity().xssProtection().and().authorizeRequests().anyRequest().fullyAuthenticated()
            .and().csrf().disable();

    http.exceptionHandling().authenticationEntryPoint(alwaysSendUnauthorized401AuthenticationEntryPoint);
}

public class AlwaysSendUnauthorized401AuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public final void commence(HttpServletRequest request, HttpServletResponse response,
            AuthenticationException authException) throws IOException {
        response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
}

}

有什么方法可以指定 spring 不重定向到/error 并返回 Bad Credentials Exception ?

最佳答案

我创建了一个示例 Spring Boot 应用程序,具有以下安全配置:

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().withUser("test").password("password").roles("USER");
    }

    @Bean
    public AuthenticationEntryPoint authenticationEntryPoint() {
        return (request, response, authException) -> response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.headers().httpStrictTransportSecurity().xssProtection()
                .and().authorizeRequests().anyRequest().fullyAuthenticated()
                .and().csrf().disable();

        http.httpBasic().authenticationEntryPoint(authenticationEntryPoint());
        http.exceptionHandling().authenticationEntryPoint(authenticationEntryPoint());

    }
}

输入无效的用户名/密码(测试/密码以外的任何内容)时,我收到以下响应:
{"timestamp":1439381390204,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/"}
org.springframework.boot.autoconfigure.web.BasicErrorController 返回此错误类,如果你看一下,它确实用 @RequestMapping("/error") 定义了两个方法- errorHtmlerror .由于您正在构建一个 API,它是应该调用的第二个 API,我会说这是“正确”的行为!

所以,首先,检查您是否正在访问 BasicErrorController当认证失败时。如果是,请确保您点击了 error方法不是 errorHtml .

如果以上都没有帮助,请检查是否有人覆盖了错误 Controller 的默认行为。一种常见(且有效)的扩展是实现您自己的 org.springframework.boot.autoconfigure.web.ErrorAttributes更改默认错误有效负载。但是更换整个 BasicErrorController 也同样容易。使用非标准实现,因此请在您的应用程序中检查它。

如果所有其他方法都失败了,并且您坚持要禁用 Spring 的默认错误处理(我不推荐),请尝试将其添加到您的配置中:
@EnableAutoConfiguration(exclude = {ErrorMvcAutoConfiguration.class})
这将确保错误 Controller 未加载到应用程序上下文中。

关于具有基本身份验证的 Spring Security 重定向到/error 以获取无效凭据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31954292/

相关文章:

mysql - Grails 中属性的自引用关系?

security - 哈希和 'brute-force' 排列

reactjs - CloudFlare JS挑战打破了我的SPA

使用 LDAP 进行 PHP 身份验证

authentication - stackoverflow 如何维护 Open-id 登录用户的数据库?

utf8 的 MYSQL 区分大小写搜索(使用 hibernate)

javascript - Spring Boot - 为什么我的应用程序找不到静态资源?

java - 在 XML 配置中引用 JavaConfig 时获取 NoSuchBeanDefinitionException

php session 安全查询

java - 使用 @Configuration 时出现 NoSuchBeanDefinitionException