尝试在springboot API中进行POST时如何在401未经授权的错误上记录请求的有效负载详细信息

问题描述

我遇到一种情况,当POST请求出现401未经授权错误时,我需要知道所请求的有效负载详细信息。 我认为,由于未授权错误而导致请求未到达API端点时,我们将无法捕获有效负载。在达到此端点之前,它将被过滤掉。

我正在使用Springboot 2.1.6

我的控制器方法如下

@PostMapping(value = "/users",produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PayloadResponse> processpayload(@RequestBody String payload) {
    logger.info("Received a payload: {}",payload);
}

有什么方法可以即使在401错误的情况下也可以通过某种方式记录此有效负载? 预先感谢

解决方法

您不能使用任何SpringMVC机制来捕获和记录这种错误,因为它发生在进入MVC堆栈之前。 @ControlerAdvice不会执行任何操作。

您可以扩展AuthenticationEntryPoint并通过进行配置

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

   protected void configure(HttpSecurity http) throws Exception {

        http.exceptionHandling()
                    .authenticationEntryPoint(new CustomAuthenticationEntryPoint())

    }
}

像这样扩展它

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest req,HttpServletResponse res,AuthenticationException authException)
            throws IOException {

        res.setContentType("application/json;charset=UTF-8");
        res.setStatus(401);
        res.getWriter().write(JsonUtil.getWriteMapper().writeValueAsString(
                new ErrorRestResponse(authException,false,""))); //This is my custom error response
        
        // You can put logging code around here

    }
}
,

您可以使用@ControllerAdvice处理各种请求,并读取它们的有效负载(如果提供),并返回适当的响应。