控制器中的验证错误返回401而不是400

时间:2019-06-06 19:33:38

标签: spring-boot spring-security spring-security-oauth2

我的rest控制器中有一个post端点,无需身份验证/授权即可访问。它是在WebSecurityConfigurerAdapter中配置的,如下所示:

@Override
public void configure(WebSecurity web) {
    web.ignoring().antMatchers("/api/v1/user");
}

端点对输入数据进行验证(由注释javax.validation.Valid提供)。当我发送无效数据时,我收到401而不是400的响应。在发送默认的spring boot 400消息的安全端点中不存在此问题。

在调试过程中,我发现在处理MethodArgumentNotValidException(在控制器中发生验证错误时引发)时,将执行WebExpressionVoter并返回值-1,这意味着“访问被拒绝”。如何配置我的应用程序以忽略对公共端点的安全性检查?

我知道使用ControllerAdvice进行异常处理是一种选择,但是是否可能有默认的400条消息?

在此先感谢您的提示!

编辑:

Security filter chain: [
  WebAsyncManagerIntegrationFilter
  SecurityContextPersistenceFilter
  HeaderWriterFilter
  LogoutFilter
  OAuth2AuthenticationProcessingFilter
  RequestCacheAwareFilter
  SecurityContextHolderAwareRequestFilter
  AnonymousAuthenticationFilter
  SessionManagementFilter
  ExceptionTranslationFilter
  FilterSecurityInterceptor
]

2 个答案:

答案 0 :(得分:0)

使用webSecurity.ignoring()将导致对该URL的请求完全绕过整个安全过滤器链。因此,有趣的是,WebExpressionVoter仍会加入这些被忽略的URL。

所以,我猜有以下可能性:

  • /api/v1/user将被重定向到其他受保护的URL。

  • 您正在考虑antMatchers("/api/v1/user")会匹配/api/v1/user下的所有URL,例如/api/v1/user/1。但是,它仅匹配/api/v1/user

要忽略/api/v1/user下的所有URL,应使用:

 web.ignoring().antMatchers("/api/v1/user/**");

答案 1 :(得分:0)

好,我找到了解决方法。我不知道为什么,但是当发生异常时,对此URL会有另一个POST请求:/ error。当我将此网址添加到我的忽略列表中后,它便开始工作。所以我的配置看起来像这样:

@Override
public void configure(WebSecurity web) {
    web.ignoring().antMatchers("/api/v1/user", "/error/**")
}

@Ken Chan感谢您提供有关调试过滤器的信息!至关重要。

相关问题