What You'll Learn

How to automatically add a username to each Logback log statement. The username relates to the user principal (identity) making a request to the application. Your application will handle more than one request at a time — if you have more than one user! — so it is important to audit who is doing what.

Specifically, we will learn:

public class UserToMdcFilter implements Filter {

  @Override
  public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain)
      throws IOException, ServletException {

    try {
      chain.doFilter(request, response);
    } finally {
      MDC.remove("user");
    }
  }

  @Override
  public void destroy() {
    // do nothing
  }

  @Override
  public void init(final FilterConfig fc) throws ServletException {
    // do nothing

  }
}

Positive reference: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-authentication-securitycontext

if ((SecurityContextHolder.getContext() != null)
        && (SecurityContextHolder.getContext().getAuthentication() != null)
        && (SecurityContextHolder.getContext().getAuthentication().getPrincipal() instanceof User)) {

        final User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        MDC.put("user", user.getUsername());
}

## Add The New Filter To The Spring Security Filter Chain Duration: 5

Positive reference: https://docs.spring.io/spring-security/site/docs/current/reference/html5/#servlet-authentication-unpwd

http.addFilterAfter(new UserToMdcFilter(), AnonymousAuthenticationFilter.class);