Spring Security authenticationEntryPoint将不适用于已提交凭据的permit()http方法

6g8kf2rb  于 2023-04-21  发布在  Spring
关注(0)|答案(1)|浏览(123)
@Override
   protected void configure(HttpSecurity httpSecurity) throws Exception
   {
      // @formatter:off
      httpSecurity
               .csrf()
               .disable()
               .authorizeRequests()
               .antMatchers(HttpMethod.GET).permitAll()
               .anyRequest()
               .authenticated()
               .and()
               .httpBasic()
               .and()
               .exceptionHandling()
               .authenticationEntryPoint(authenticationEntryPoint());
      // @formatter:on
   }

   private static AuthenticationEntryPoint authenticationEntryPoint()
   {
      return (request, response, authException) -> {
         response.addHeader("WWW-Authenticate", "Basic realm=\"Realm\"");
         response.setContentType(MediaType.APPLICATION_JSON_VALUE);
         response.setStatus(HttpStatus.UNAUTHORIZED.value());
         String message = authException.getMessage();
         if (request.getHeaders("Authorization").hasMoreElements()) {
            message += ". Wrong Authorization Key.";
         } else {
            message += ". Missing Authorization Key im Header.";
         }
         response.getWriter().format("""
                                              {
                                                "errors":[
                                                  {
                                                    "status": %d,
                                                    "title": "%s",
                                                    "detail": "%s"
                                                  }
                                                ]
                                              }
                                              """,
                                     HttpStatus.UNAUTHORIZED.value(),
                                     HttpStatus.UNAUTHORIZED.name(),
                                     message
         );
      };
   }

为什么我用错误的凭据发送帖子请求,我得到了:

{
    "errors": [
        {
            "status": 401,
            "title": "UNAUTHORIZED",
            "detail": "Full authentication is required to access this resource. Wrong Authorization Key."
        }
    ]
}

对于get方法,我没有得到格式化错误:

{
    "timestamp": "2023-04-18T17:07:35.663+00:00",
    "status": 401,
    "error": "Unauthorized",
    "path": "/xxx/1111"
}

我也得到了一个漂亮的回应,就像一个帖子

mbskvtky

mbskvtky1#

spring security中有一个已知的bug/功能,如果在permitAll()被命中之前很久就有一个Authorization header,则会导致请求被“验证”。我相信这就是我们所观察到的。除非凭证有效,否则不要传递凭证。

相关问题