How to retrieve and log the current user with Auth0 / Spring Boot / Spring Security?

Hello,

I developed a SPA with a Spring Boot API secured with auth0-spring-security-api 1.1.0 (and I’m really happy with it). For audit purposes, I would like to log all the user for all API requests. I first thought I could easily do that in a filter with SecurityContextHolder.getContext().getAuthentication() but that returns null.

I noticed that I am not the first one trying to achieve that, unfortunately I could not find any answer so far:

How could this be achieved?

Thanks

Oops, for some reason I was wrong, I can finally get a user ID with SecurityContextHolder.getContext().getAuthentication().getName().

However, this returns a string like this: waad|aBCDHi0JkLM1nOpQRSt2U_3VWXyzAbCdEFg4HIJ567k (we’re using Microsoft Azure AD /Office 365 for enterprise login)

Is there any way I can get the user details (name or email) through this AuthenticationJsonWebToken object?
If not, how can I (afterwards) find the user behind this token through the Auth0 admin dashboard / management API?

Thanks

I could not find an easy way to log the user email so this is the best solution I found so far (logging the user_id):

import com.google.common.annotations.VisibleForTesting;
import org.slf4j.MDC;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

/**
 * Attach a user identifier to requests / responses / logs for auditing
 * User details can be found in the Auth0 Dashboard: https://manage.auth0.com/#/users -> Search the "user_id" by Lucene Syntax
 */
@Component
public class UserIdFilter extends GenericFilterBean {

  private static final String MDC_KEY = "userId";

  @Override
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    if (getAuthentication() != null) {
      MDC.put(MDC_KEY, getAuthentication().getName());
    }
    try {
      chain.doFilter(request, response);
    } finally {
      MDC.remove(MDC_KEY);
    }
  }

  @VisibleForTesting
  Authentication getAuthentication() {
    return SecurityContextHolder.getContext().getAuthentication();
  }

  @VisibleForTesting
  String get() {
    return MDC.get(MDC_KEY);
  }
}

This topic was automatically closed 15 days after the last reply. New replies are no longer allowed.