c# - 如何使用声明

标签 c# asp.net-web-api owin katana asp.net-identity-2

我有一个使用 Asp.NET-Identity 2.0(代码优先)进行身份验证的 Web API 2.1。

我的问题是更新/删除用户声明,AuthenticationType 是“Bearer”。我有一个名为“实例”的声明,我想更新它。我有一个派生自 OAuthAuthorizationServerProvider 的 authprovider,我覆盖了 GrantResourceOwnerCredentials,所以它看起来像这样:

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 中我有一个函数来更新声明“实例”。

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 { });

但下次我尝试从用户那里获取“实例”时,它仍然具有值“测试”。我错过了什么?

最佳答案

您不能修改与 token “相关”的声明。 token 基于声明和服务器 machine.config。

最好的解决方案是使用刷新 token 。

关于c# - 如何使用声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23779593/

相关文章:

asp.net-web-api - 间歇性 "Could not load type ' System.Net.Http.Formatting.FormUrlEncodedMediaTypeFormatter'"错误

c# - Web API引发验证错误

c# - 一个中间件应该总是调用下一个?

c# - 针对自托管 Web API (OWIN/Katana) 验证 MVC 客户端

c# - TextBlock 中的绑定(bind)在 WPF 中不起作用

c# - 相当于 Prism ViewModels 中的 WPF DependencyProperties

c# - UWP DataContext 从 DataTempalte 到 DataTemplate 中的 UserControl

c# - 被视为 "int"的动态变量可以溢出吗?

c# - 无法在 WebApi 响应中设置 Content-MD5 header

c# - OWin 是否支持 WCF?