Search code examples
c#asp.netasp.net-coreclaims-based-identity.net-security

How to manipulate the ClaimsIdentity of current token using middleware in .net core app?


I have a middleware to use in development mode like following.

public class DevelopmentUserMiddleware
{
    private readonly RequestDelegate _next;

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

    public async Task InvokeAsync(HttpContext context)
    {
        context.Request.HttpContext.User = new ClaimsPrincipal(
            new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.NameIdentifier, "75cc7127-a31c-418b-b580-27379136b148"),
                new Claim(ClaimTypes.Name, "Name Surname")
            }));
        
        await _next(context);
    }
}

So I can use name or id value on development platform. And getting values using an extension method var usriId = User.GetUserId();.

public static class ClaimsPrincipalExtensions
{
    public static Guid GetUserId(this ClaimsPrincipal principal)
    {
        if (principal == null)
            throw new ArgumentNullException(nameof(principal));
      
        return Guid.Parse(principal.FindFirstValue(ClaimTypes.NameIdentifier));
    }

    public static string GetName(this ClaimsPrincipal principal)
    {
        if (principal == null)
            throw new ArgumentNullException(nameof(principal));

        return principal.FindFirstValue(ClaimTypes.Name);
    }
}

But now, I am using Bearer access token while using api resource. If the user nameidenitfier is "123456" in the access token, the User.GetUserId() method returns "123456". My middleware does not work.

So can I change only name and nameidentifier of access token in development mode?


Solution

  • According to your description, I suggest you could read the claims from the conetext and modify it instead of recreate a new claims identity.

    More details, you could use below codes.

    public class DevelopmentUserMiddleware
    {
        private readonly RequestDelegate _next;
    
        public DevelopmentUserMiddleware(RequestDelegate next)
        {
            _next = next;
        }
    
        public async Task InvokeAsync(HttpContext context)
        {
            string token = context.Request.Headers["Authorization"];
            if (!string.IsNullOrEmpty(token))
            {
                List<Claim> claims = context.User.Claims.ToList();
                claims.Remove(claims.First(x => x.Type == ClaimTypes.NameIdentifier));
                claims.Add(new Claim(ClaimTypes.NameIdentifier, "75cc7127-a31c-418b-b580-27379136b148"));
                claims.Remove(claims.First(x => x.Type == ClaimTypes.Name));
                claims.Add(new Claim(ClaimTypes.Name, "Name Surname"));
                var userIdentity = new ClaimsIdentity(claims, ClaimTypes.Name);
                context.User = new ClaimsPrincipal(userIdentity);
            }
            await _next(context);
        }
    }
    

    Result:

    enter image description here