簡體   English   中英

嘗試在 springboot API 中 POST 時,如何在 401 Unauthorized 錯誤上記錄請求的有效負載詳細信息

[英]How to log requested payload details on 401 Unauthorized error when try to POST in springboot API

我有一種情況,當 POST 請求出現 401 Unauthorized 錯誤時,我需要知道請求的有效負載詳細信息。 我認為當請求由於未授權錯誤而未發送到 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處理各種請求並讀取它們的有效負載(如果提供),並返回適當的響應。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM