User Context Enrichment in ASPNET Core Request Tracing

Listen to this Post

Featured Image
Implementing user context enrichment in ASP.NET Core request tracing enhances observability by tracking user journeys and simplifying issue troubleshooting. Below are key lessons and practical steps to achieve this effectively.

5 Key Lessons Learned

  1. Use Middleware to Extract User IDs from Claims
    Middleware can capture user details from authentication claims early in the request pipeline.

  2. Add User Context to Activity Tags and Logging Scopes
    Enrich OpenTelemetry (OTEL) activities and logs with user-specific metadata.

3. Place Middleware After Authentication

Ensure the middleware runs post-authentication to access validated user claims.

  1. Expand Context with Feature Flags and Tenant Info
    Include business-specific data like tenant IDs or feature toggle states.

5. Avoid PII in Logs

Mask sensitive user data to comply with privacy regulations.

You Should Know: Practical Implementation

1. Middleware for User Context Extraction

public class UserContextMiddleware 
{ 
private readonly RequestDelegate _next;

public UserContextMiddleware(RequestDelegate next) 
{ 
_next = next; 
}

public async Task InvokeAsync(HttpContext context) 
{ 
var userId = context.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; 
if (userId != null) 
{ 
// Add to Activity (OTEL) 
Activity.Current?.SetTag("user.id", userId);

// Add to Logging Scope 
using (LogContext.PushProperty("UserId", userId)) 
{ 
await _next(context); 
} 
} 
else 
{ 
await _next(context); 
} 
} 
} 

2. Register Middleware in `Program.cs`

app.UseAuthentication(); 
app.UseAuthorization(); 
app.UseMiddleware<UserContextMiddleware>(); 

3. Enrich OTEL Activities Globally

services.AddOpenTelemetry() 
.WithTracing(builder => 
{ 
builder.AddAspNetCoreInstrumentation() 
.AddProcessor(new ActivityEnrichmentProcessor()); 
});

public class ActivityEnrichmentProcessor : BaseProcessor<Activity> 
{ 
public override void OnStart(Activity activity) 
{ 
var userId = HttpContext.Current?.User?.FindFirst(ClaimTypes.NameIdentifier)?.Value; 
if (userId != null) 
{ 
activity.SetTag("user.id", userId); 
} 
} 
} 

4. Logging with Serilog (Structured Logs)

Log.Logger = new LoggerConfiguration() 
.Enrich.FromLogContext() 
.WriteTo.Console(outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {UserId} {Message}{NewLine}{Exception}") 
.CreateLogger(); 

5. Secure PII Handling

// Hash or mask sensitive data 
activity.SetTag("user.email", MaskEmail(user.Email));

private string MaskEmail(string email) 
{ 
return Regex.Replace(email, @"(?<=.).(?=.@)", ""); 
} 

What Undercode Say

Enhancing ASP.NET Core tracing with user context improves debugging and compliance. Key takeaways:
– Linux Command: Use `journalctl -u your-aspnet-service` to inspect enriched logs.
– Windows Command: Filter Event Viewer logs via Get-WinEvent -FilterHashtable @{LogName='Application'}.
– Kibana Query: `user.id:”12345″` to track user-specific traces in Elasticsearch.
– Grafana Dashboard: Visualize user journey metrics with Prometheus.

For further reading, check Milan Jovanović’s guide: https://lnkd.in/e4M3UNPi.

Expected Output:

  • Structured logs with `UserId` in every entry.
  • OTEL traces tagged with `user.id` in Jaeger/Zipkin.
  • Secure PII handling in compliance with GDPR.

References:

Reported By: Milan Jovanovic – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅

Join Our Cyber World:

💬 Whatsapp | 💬 Telegram