C# 如何使用索赔
我有一个Web API 2.1,它使用Asp.NET-Identity 2.0(代码优先)进行身份验证 我的问题是升级/删除用户声明,AuthenticationType为“Bearer”。我有一个名为“实例”的声明,我想更新它。我有一个从OAuthAuthorizationServerProvider派生的authprovider,我覆盖了GrantResourceOwnerCredentials,所以它看起来像这样:C# 如何使用索赔,c#,asp.net-web-api,owin,katana,asp.net-identity-2,C#,Asp.net Web Api,Owin,Katana,Asp.net Identity 2,我有一个Web API 2.1,它使用Asp.NET-Identity 2.0(代码优先)进行身份验证 我的问题是升级/删除用户声明,AuthenticationType为“Bearer”。我有一个名为“实例”的声明,我想更新它。我有一个从OAuthAuthorizationServerProvider派生的authprovider,我覆盖了GrantResourceOwnerCredentials,所以它看起来像这样: var user = await userManager.FindAsyn
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);
然后在我的UserController中,我有一个更新声明“实例”的函数
但是下次我试图从用户那里获取“实例”时,它仍然有值“test”。我遗漏了什么?您不能修改与令牌“相关”的声明。令牌基于声明和server machine.config
最好的解决方案是使用刷新令牌
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 { });