The requirement is to log principal with a request id (randomly generated) so that the request-id can be used to search through logs to know who has made the request.
We are using Spring reactive, MDC (to log multiple components together), and web filter for logging purposes. The goal is to do an MDC.put on principal.
The web filter:
public class WebFilterLogging implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
long time = System.currentTimeMillis();
BodyCaptureExchange bodyCaptureExchange = new BodyCaptureExchange(exchange);
// TODO:add logged in user information
return chain.filter(bodyCaptureExchange).doOnError(err -> {
long latencyInMs = System.currentTimeMillis() - time;
MDC.put("request-id", bodyCaptureExchange.getRequest().getId());
MDC.put("request-method", bodyCaptureExchange.getRequest().getMethod());
MDC.put("request-url", bodyCaptureExchange.getRequest().getPath());
MDC.put("query-params", bodyCaptureExchange.getRequest().getQueryParams());
MDC.put("host-ip", EcsService.getContainerIP());
MDC.put("user-id", exchange.getPrincipal());
log.info("{\"requestBody\":" + bodyCaptureExchange.getRequest().getFullBody() + "}");
log.error("{\"responseBody\":" + "\"" + err.getLocalizedMessage() +"\"" + "," +
" \"responseCode\":"+ err.getLocalizedMessage().split(" ")[0] + "," +
" \"latencyInMs\":" + latencyInMs + "}");
}).doOnSuccess(se -> {
long latencyInMs = System.currentTimeMillis() - time;
MDC.put("request-id", bodyCaptureExchange.getRequest().getId());
MDC.put("request-method", bodyCaptureExchange.getRequest().getMethod());
MDC.put("request-url", bodyCaptureExchange.getRequest().getPath());
MDC.put("query-params", bodyCaptureExchange.getRequest().getQueryParams());
MDC.put("host-ip", EcsService.getContainerIP());
MDC.put("user-id", exchange.getPrincipal());
log.info("{\"requestBody\":" + bodyCaptureExchange.getRequest().getFullBody() + "}");
log.info("{\"responseBody\":" + bodyCaptureExchange.getResponse().getFullBody() + "," +
" \"latencyInMs\":" + latencyInMs + "," +
" \"responseCode\":" + bodyCaptureExchange.getResponse().getRawStatusCode() + "}");
});
}
}
exchange.getPrincipal() - returns a Mono (requirement is String) actually returns: "MonoMapFusable" as output I have tried using a map and a flat map after getPrincipal() but it returns a "MonoMapFusable" as output
I have tried retrieving the principal through ReactiveSecurityContext as well but that also returns a Mono, and not a String
My question is, is there a way to work with ServerWebExchange to retrieve the principal the goal is to log the principal/user name of the user who made the request