春季安全使用基本身份验证重定向到无效凭据/错误 [英] Spring Security with basic auth redirecting to /error for invalid credentials

查看:1793
本文介绍了春季安全使用基本身份验证重定向到无效凭据/错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须使用基本身份验证与春季安全运行的春天启动应用程序。
当正确的基本身份验证凭据提供的,一切都是美好的,但不正确的身份验证凭据,春天来了一个的Htt prequestMethodNotSupportedException:请求方法POST不支持例外

I have a spring boot application running with spring security using basic auth. When proper basic auth credentials are supplied, everything is good, but for incorrect auth credentials, spring comes up with a HttpRequestMethodNotSupportedException: Request method 'POST' not supported exception.

根据日志,认证失败已确定春天,但是这不是什么出来。

According to the logs, the authentication failure has been identified by spring, but that's not what comes out.

2015年8月12日09:33:10.922 INFO 16988 --- [NIO-8080-EXEC-4] osbaaudit.listener.AuditListener:AuditEvent [时间戳=周三08月12日09:33 :10 AEST 2015年,本金= anonymousUser,键入= AUTHORIZATION_FAILURE,数据= {类型= org.springframework.security.access.AccessDeniedException,消息=访问被拒绝}]
2015年8月12日09:33:10.927 TRACE 16988 --- [NIO-8080-EXEC-4] osweb.servlet.DispatcherServlet:绑定请求上下文线索:FirewalledRequest [org.apache.catalina.core.ApplicationHtt $ P $ @ pquest 483e1fc6]
2015年8月12日09:33:10.927 DEBUG 16988 --- [NIO-8080-EXEC-4] o.s.web.servlet.DispatcherServlet:DispatcherServlet的与名的DispatcherServlet处理POST请求[/所有MyApplication /错误]
2015年8月12日09:33:10.927 TRACE 16988 --- [NIO-8080-EXEC-4] osweb.servlet.DispatcherServlet:测试处理器图[org.springframework.web.servlet.handler.SimpleUrlHandlerMapping@331bb032]中一个名为DispatcherServlet的'DispatcherServlet的
2015年8月12日09:33:10.927 TRACE 16988 --- [NIO-8080-EXEC-4] o.s.w.s.handler.SimpleUrlHandlerMapping:找不到处理程序映射[/错误]
2015年8月12日09:33:10.927 TRACE 16988 --- [NIO-8080-EXEC-4] osweb.servlet.DispatcherServlet:测试处理器图[org.springframework.boot.actuate.endpoint.mvc.EndpointHandlerMapping@69e79b9b在DispatcherServlet的名为'的DispatcherServlet
2015年8月12日09:33:10.927 TRACE 16988 --- [NIO-8080-EXEC-4] osweb.servlet.DispatcherServlet:测试处理器图[org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping @ 27cc0354在DispatcherServlet的名为'的DispatcherServlet
2015年8月12日09:33:10.927 DEBUG 16988 --- [NIO-8080-EXEC-4] s.w.s.m.m.a.RequestMappingHandlerMapping:仰望处理程序路径/错误方法
2015年8月12日09:33:10.928 DEBUG 16988 --- [NIO-8080-EXEC-4] .mmaExceptionHandlerExceptionResolver:解决由异常处理[空]:org.springframework.web.Htt prequestMethodNotSupportedException:请求方法POST不支持

通过上面的日志和放大器;调试春源后,我发现,在识别的凭据是不正确的,春天创建一个BadCredentials异常,然后试图重定向到/错误,这种重定向是什么原因造成的HttpMethodNotAllowed例外。(我的应用程序没有A /错误端点)。

With the above logs & after debugging the spring source, I found out that upon identifying that the credentials are incorrect, spring creates a BadCredentials exception and then tries to redirect to "/error", this redirection is what causes the HttpMethodNotAllowed exception.(my application doesn't have a /error endpoint).

我想告诉春天不是通过配置以下,

I tried to tell spring not to use /error by configuring the following,

`公共类ServerCustomization扩展ServerProperties {

`public class ServerCustomization extends ServerProperties {

@Override
public void customize(ConfigurableEmbeddedServletContainer container) {

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

}`

这会使弹簧挡吐出的HttpMethodnotallowed异常,并让它拿出一个401,但我的这个异常没有被我的异常处理程序使用捕获(配置 @ControllerAdvice )。

This will make spring stop spitting out the HttpMethodnotallowed exception and make it come up with a 401(Unauthorized), BUT my this exception is not caught by my Exception handler (configured using @ControllerAdvice).

我也试过配置自定义身份验证入口点像下面没有任何运气。

I also tried configuring a custom authentication entry point like below without any luck.

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

}

有没有我们可以指定弹簧不能重定向到/错误并返回坏证书例外?任何方式

Is there any way we can specify to spring not to redirect to /error and return the Bad Credentials Exception ?

推荐答案

我创建了一个示例春天启动的应用程序,具有以下安全配置:

I created a sample Spring Boot app, with the following security config:

@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());

    }
}

当输入无效的用户名/密码(不是测试/密码,任何其他),我得到以下回应:

When entering an invalid username/password (anything other than test/password), I get the following response:

{"timestamp":1439381390204,"status":401,"error":"Unauthorized","message":"Bad credentials","path":"/"}

此错误是由 org.springframework.boot.autoconfigure.web.BasicErrorController 类,如果你看看它定义了两个方法与 @RequestMapping(/错误) - errorHtml 错误。既然你正在构建一个API,它应调用第二个,我会说这是正确的行为!

This error is returned by org.springframework.boot.autoconfigure.web.BasicErrorController class, which if you have a look does define two methods with @RequestMapping("/error") - errorHtml and error. Since you're building an API, it's the second one that should be invoked and I would say that's the "correct" behaviour!

所以,首先,检查你得到的 BasicErrorController 时,认证失败。如果是,请确保你打的错误方法不仅 errorHtml

So, first thing, check that you're getting to the BasicErrorController when authentication fails. If you are, make sure that you're hitting the error method NOT errorHtml.

如果没有以上的证明有益的,检查是否有人重写错误控制器的默认行为。一个常见的​​(有效)扩展是实现自己的 org.springframework.boot.autoconfigure.web.ErrorAttributes 来改变默认的错误有效载荷。但它只是作为易于使用非标准的实现替换整个 BasicErrorController ,所以检查,在您的应用程序。

If none of the above proves helpful, check whether someone has overriden the default behaviour of the error controller. One common (and valid) extension is to implement your own org.springframework.boot.autoconfigure.web.ErrorAttributes to change the default error payload. But it's just as easy to replace the entire BasicErrorController with a non-standard implementation, so check for that in your application.

如果一切都失败了,你就坚决认为要禁用Spring的默认错误处理(我不推荐),你可以添加以下到您的配置:

If all else fails and you're adamant that you want to disable Spring's default error handling (which I don't recommend), try adding this to your configuration:

@EnableAutoConfiguration(不含= {} ErrorMvcAutoConfiguration.class)

这将完成是确保误差控制器不会装入应用程序上下文。

What this will do is ensure that the error controllers are not loaded into the application context.

这篇关于春季安全使用基本身份验证重定向到无效凭据/错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆