I have some middleware designed to perform some logic. Part of that logic is to update the claim value after user is authenticated. I am wondering if it is possible to do so?
public class MyMiddleware
{
public async Task Invoke(HttpContext context)
{
//logic omitted
var claims = new List<Claim> { new Claim("MyValue", "test") }
context.User.AddIdentity(new ClaimsIdentity(claims));
}
}
The only approach I have found so far is in the example above. However, I don't fully understand this approach. Will the above override any existing claims or will it have some other behavior?
Edit: In my testing, the above code does not works. As in the claim is never actually added when I look at it on my next request.
I have also tried the below but it had the same effect, claims did not persist on next request.
public class MyMiddleware
{
public async Task Invoke(HttpContext context)
{
//logic omitted
var claimsIdentity = (ClaimsIdentity) context.User.Identity;
var identity = new ClaimsIdentity(claimsIdentity);
var myClaim = identity.Claims.FirstOrDefault(x => x.Type.Equals(userExpirationName));
if(myClaim != null) identity.RemoveClaim(myClaimName);
identity.AddClaim(new Claim(myClaimName, "test"));
context.User.AddIdentity(identity);
}
}