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

倾然丶 夕夏残阳落幕 提交于 2020-12-15 05:17:05

问题


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 = "/users", produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<PayloadResponse> processPayload(@RequestBody String payload) {
    logger.info("Received a payload: {}", payload);
}

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


回答1:


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("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

    }
}



回答2:


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



来源:https://stackoverflow.com/questions/63852145/how-to-log-requested-payload-details-on-401-unauthorized-error-when-try-to-post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!