Extracting User Information in ASPNET Core Using UserContext

Listen to this Post

Most modern APIs are stateless by default, but accessing the current user’s information efficiently is crucial. In ASP.NET Core, you can achieve this using a `UserContext` class that extracts user details from claims via HttpContext.

How to Implement UserContext in ASP.NET Core

Here’s a practical implementation:

public class UserContext 
{ 
private readonly IHttpContextAccessor _httpContextAccessor;

public UserContext(IHttpContextAccessor httpContextAccessor) 
{ 
_httpContextAccessor = httpContextAccessor; 
}

public string UserId => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.NameIdentifier); 
public string Username => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Name); 
public string Email => _httpContextAccessor.HttpContext?.User?.FindFirstValue(ClaimTypes.Email); 
}

Register it in `Program.cs`:

builder.Services.AddHttpContextAccessor(); 
builder.Services.AddScoped<UserContext>(); 

You Should Know:

  1. Testing UserContext – Use integration tests with TestServer:
    var server = new TestServer(new WebHostBuilder().UseStartup<Startup>()); 
    var client = server.CreateClient(); 
    

  2. Middleware Alternative – Avoid `HttpContextAccessor` dependency by setting user data in middleware:

    app.Use(async (context, next) => 
    { 
    var userContext = context.RequestServices.GetRequiredService<UserContext>(); 
    // Set user data 
    await next(); 
    }); 
    

  3. Multi-Tenancy Handling – Extend `UserContext` to include tenant IDs:

    public string TenantId => _httpContextAccessor.HttpContext?.User?.FindFirstValue("TenantId"); 
    

  4. Linux/Windows Logs for Debugging – Check ASP.NET Core logs:

    journalctl -u dotnet-app --no-pager -n 50  Linux 
    Get-EventLog -LogName Application -Source "ASP.NET Core" -Newest 20  Windows 
    

  5. JWT Token Validation – Verify tokens using OpenSSL:

    openssl jwt -decode -no-verify -input <token> 
    

What Undercode Say

The `UserContext` pattern simplifies user data access but should be used judiciously. Avoid excessive reliance on `HttpContext` in non-HTTP scenarios. Instead, consider middleware or request pipelines for better testability. For multi-tenant apps, ensure tenant isolation. Always log user context actions for security audits.

Expected Output:

A reusable `UserContext` class integrated with ASP.NET Core’s DI, tested via middleware or integration tests, and extended for multi-tenancy.

Reference:

References:

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

Join Our Cyber World:

💬 Whatsapp | 💬 TelegramFeatured Image