Search code examples
c#asp.net-web-apiowinkatanaasp.net-identity-2

How to use claims


I have a Web API 2.1 that is using Asp.NET-Identity 2.0 (code-first) for authentication.

My problem is to updare/remove an user claims, the AuthenticationType is "Bearer". I have a claim called "instance", and I want to update it. I have an authprovider that derives from OAuthAuthorizationServerProvider and I override the GrantResourceOwnerCredentials so it look like this:

var user = await userManager.FindAsync(context.UserName, context.Password);

var identity = new ClaimsIdentity(new[] 
    { 
        new Claim(ClaimTypes.Name, user.UserName) 
    }, 
    context.Options.AuthenticationType, 
    ClaimTypes.Name, 
    ClaimTypes.Role);

identity.AddClaim(new Claim(ClaimTypes.NameIdentifier, user.Id));
identity.AddClaim(new Claim(ClaimTypes.Instances, "test"));

var ticket = new AuthenticationTicket(identity, new AuthenticationProperties());

context.Validated(ticket);

Then in my UserController i have a function to update the claim "instance".

var user = (ClaimsIdentity)User.Identity;
var insClaim = user.Claims.Single(x => x.Type == ClaimTypes.Instances);

user.RemoveClaim(insClaim);
user.AddClaim(new Claim(ClaimTypes.Instances, "TEST 123"));

var ctx = Request.GetOwinContext();
var authCtx = await ctx.Authentication.AuthenticateAsync(user.AuthenticationType);

if (authCtx != null)
{
    ctx.Authentication.SignOut(user.AuthenticationType);
    ctx.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(user, authCtx.Properties);
    ctx.Authentication.SignIn(user);
}

return Ok(new { });

But the next time I'm trying to get the "instance" from the user it still has the value "test". What am I missing?


Solution

  • You cant modify claims "related" to a token. The token is based on the claims and the server machine.config.

    The best solution is to use refresh token.