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

huangapple go评论77阅读模式
英文:

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

问题

以下是翻译好的部分:

当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错误时以某种方式记录这个载荷?
提前感谢您的帮助。

英文:

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.

I am using Springboot 2.1.6

My controller method as below

@PostMapping(value = &quot;/users&quot;, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity&lt;PayloadResponse&gt; processPayload(@RequestBody String payload) {
    logger.info(&quot;Received a payload: {}&quot;, payload);
}

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

答案1

得分: 1

你不能使用任何SpringMVC机制来捕获和记录这种类型的错误,因为它发生在进入MVC堆栈之前。@ControllerAdvice 无法起作用。

你可以扩展 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, ""))); // 这是我的自定义错误响应
        
        // 你可以在这里添加日志记录代码

    }
}
英文:

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.

You can extend AuthenticationEntryPoint and config it by

@EnableWebSecurity
public class WebSecurity extends WebSecurityConfigurerAdapter {

   protected void configure(HttpSecurity http) throws Exception {

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

    }
}

extend it like this

public class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {

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

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

    }
}

答案2

得分: 0

你可以使用@ControllerAdvice来处理各种请求并读取它们提供的有效载荷,然后返回相应的响应。

英文:

you can use a @ControllerAdvice to handle all kinds of requests and read their payloads if supplied, and give back the appropriate response.

huangapple
  • 本文由 发表于 2020年9月12日 02:02:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/63852145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定