PhilKes
PhilKes

Reputation: 138

OpenTelemetry Java agent extension to add Spring authenticated User id in Span attributes

I have a Spring Boot 2.7.5 application running with an opentelemetry-javaagent.jar that includes some custom extensions. I now want to add a custom SpanProcessor that adds an attribute userId to all Spans corresponding to incoming HTTP Requests to the Spring REST API. How can I do that?

In Spring I would get the authenticated user's id/information with:

SecurityContextHolder.getContext().getAuthentication();

But can I access the Spring Security Context from within the SpanProcessor in my javaagent?

I tried finding an example of a otel-javaagent extension accessing any Spring Beans but could not find any yet.

Upvotes: 0

Views: 1032

Answers (1)

trask
trask

Reputation: 716

OpenTelemetry Java agent extensions live in the isolated AgentClassLoader which is why they don't have access to Spring classes.

I'd suggest:

  • Add the userId to the SERVER span at the beginning of the request

    • (as a side note, this seems like it would be a nice addition to the OpenTelemetry auto-instrumentation, since there's already an OpenTelemetry attribute to store it in enduser.id)
  • In your SpanProcessor, copy the userId down from parent to child, e.g.

    @Override
    @SuppressWarnings("unchecked")
    public void onStart(Context parentContext, ReadWriteSpan span) {
      Span parentSpan = Span.fromContextOrNull(parentContext);
      if (!(parentSpan instanceof ReadableSpan)) {
        return;
      }
      ReadableSpan parentReadableSpan = (ReadableSpan) parentSpan;
    
      ...
    }
    

Upvotes: 1

Related Questions