尝试在 springboot API 中 POST 时,如何在 401 Unauthorized 错误上记录请求的有效负载详细信息 [英] How to log requested payload details on 401 Unauthorized error when try to POST in springboot API

查看:32
本文介绍了尝试在 springboot API 中 POST 时,如何在 401 Unauthorized 错误上记录请求的有效负载详细信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a situation I would need to know the requested payload details when the POST request got 401 Unauthorized error. I am thinking we will NOT be able to capture the payload when the request has NOT made it to the API endpoint due to Unauthorized error. It will be filtered out before hitting this endpoint.

我使用的是 Springboot 2.1.6

I am using 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 错误,我们有什么方法可以以某种方式记录此有效负载吗?提前致谢

Are there any ways we can log this payload somehow even on 401 error? Thanks in advance

推荐答案

您不能使用任何 SpringMVC 机制来捕获和记录此类错误,因为它发生在进入 MVC 堆栈之前.@ControlerAdvice 不会做任何事情.

You cannot use any of SpringMVC mechanisms to catch and log this kind of error because it happens before going in MVC stack. @ControlerAdvice won't do a thing.

您可以扩展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

    }
}

这篇关于尝试在 springboot API 中 POST 时,如何在 401 Unauthorized 错误上记录请求的有效负载详细信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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