spring-security spring安全许可均考虑基本身份验证通过并验证

yruzcnhs  于 2022-11-11  发布在  Spring
关注(0)|答案(1)|浏览(204)

我最近在Spring Security上进行POC,发现了一些奇怪的行为。如果客户端使用基本身份验证调用API端点,则配置为permit all的该端点将对请求进行身份验证。示例代码:

http
        .authorizeRequests()
        .antMatchers(HttpMethod.GET, "/health").permitAll()
        .anyRequest().authenticated()
        .and()
        .httpBasic().authenticationEntryPoint(entryPoint)
        .and()
        .csrf().disable()
        .cors().and()
        .formLogin().disable();
        return http.build();

使用curl进行如下调用时会出现错误:

curl -X GET -u "user:password" -H Content-Type:application/json http://localhost:20000/health

错误:

{"responseCode":401,"responseStatus":"Unauthorized","errorMessage":["Not authorized to access"],"responseMsg":null}

如果调用curl命令时没有用户名和密码,那么curl命令将工作并返回所需的响应。请任何人建议这是否是正确的行为以及如何覆盖它。
身份验证入口点实现:

public class MyAuthenticationEntryPoint implements AuthenticationEntryPoint{

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response,
        AuthenticationException authException) throws IOException, ServletException {

        ResponseData responseData = new ResponseData();
        responseData.setResponseStatus(HttpStatus.UNAUTHORIZED.getReasonPhrase());
        responseData.setErrorMessage(new ArrayList<>(Arrays.asList("Not authorized to access")));
        responseData.setResponseCode(HttpServletResponse.SC_UNAUTHORIZED);

          ObjectMapper mapper = new ObjectMapper();
          mapper.configure(JsonParser.Feature.ALLOW_COMMENTS, true);
          String jsonResponse = mapper.writeValueAsString(responseData);
          PrintWriter printWriter = response.getWriter(); 
          printWriter.append(jsonResponse);
             printWriter.flush();
             printWriter.close();
      }
}
cxfofazt

cxfofazt1#

permitAll并不意味着没有身份验证,它只是说明不会对该端点进行授权检查。因此,如果您启用了httpBasic并在请求中发送凭据,则BasicAuthenticationFilter将根据您的UserDetailsService检查凭据。
我想你的证件是错误的,这就是为什么你收到401。

相关问题