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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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:

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


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x