Palmi
Palmi

Reputation: 2521

ASP NET Core: Overwrite Username of HttpContext

Is there a way to set the user name in an ASP NET Core application via Middleware?

I created a AnonymousUserMiddleware:

    public AnonymousUserMiddleware(RequestDelegate next, HttpContextCurrentClaimsPrincipalAccessor currentClaimsPrincipalAccessor, ILogger<AnonymousUserMiddleware> logger)
    {
        _next = next;
        _currentClaimsPrincipalAccessor = currentClaimsPrincipalAccessor;
        _logger = logger;
    }

    public async Task Invoke(HttpContext context)
    {
        try
        {
            _currentClaimsPrincipalAccessor?.Current?.Identity?.Name = "anonymous";
            await _next.Invoke(context);
        }
        catch (Exception ex)
        {
            _logger.LogError(1, ex, "Exception");
            throw ex;
        }
    }

But this doesn't work, because Name is a readonly field.

I want to call this in the Startup.cs when in Developer-Mode so that the user name is always "anonymous" during a request.

Is there a way to accomplish this?

Upvotes: 1

Views: 1557

Answers (1)

Ralf B&#246;nning
Ralf B&#246;nning

Reputation: 15425

You can build your own ClaimsPrincipal and assign the instance to the HttpContext. For example:

public async Task Invoke(HttpContext context)
{
    try
    {
        var identity = new ClaimsIdentity();
        identity.AddClaim(new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", "anonymous", "http://www.w3.org/2001/XMLSchema#string"));

        var principal = new ClaimsPrincipal();
        principal.AddIdentity(identity);

        context.User = principal;

        await _next.Invoke(context);
    }
    catch (Exception ex)
    {
        _logger.LogError(1, ex, "Exception");
        throw ex;
    }
}

Upvotes: 1

Related Questions