【发布时间】:2014-12-21 19:03:00
【问题描述】:
我无法让 ASP 标识按需刷新其存储在 cookie 中的标识。
在Startup.Auth.cs 文件中,cookie 设置为重新生成,如下所示:
app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
LoginPath = new PathString("/Account/Login"),
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<QuizSparkUserManager, QuizSparkUser, int>(
validateInterval: TimeSpan.FromMinutes(30),
regenerateIdentityCallback: ((manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie)),
getUserIdCallback: ((claimsIdentity) => int.Parse(claimsIdentity.GetUserId())))
}
});
但是我不知道如何在代码中刷新 User.Identity 上的内容,即在我需要刷新身份 cookie 时强制刷新它。
我希望能够以编程方式使用重新生成身份回调,这可能吗?
我的问题和这个类似:How to invalidate .AspNet.ApplicationCookie after Adding user to Role using Asp.Net Identity 2?
但是我想刷新而不是使 cookie 无效。
编辑
查看链接的问题后,我尝试了以下操作(没有完整的错误处理):
IOwinContext context = Request.GetOwinContext();
QuizSparkSignInManager manager = context.Get<QuizSparkSignInManager>();
ClaimsIdentity newIdentity = manager.CreateUserIdentity(manager.UserManager.FindById(User.Identity.GetUserId<int>()));
AuthenticateResult authenticationContext =
await context.Authentication.AuthenticateAsync(DefaultAuthenticationTypes.ApplicationCookie);
if (authenticationContext != null)
{
context.Authentication.AuthenticationResponseGrant = new AuthenticationResponseGrant(
newIdentity, authenticationContext.Properties);
}
bool first2 = User.IsInRole("Turtle");
Edit2:但是用户似乎仍然没有刷新。在页面重新加载时,它们似乎确实刷新了,我是否认为这是因为 User.Identity cookie 是请求的一部分并且不能在代码中更改?
【问题讨论】:
-
你想通过刷新 cookie 做什么?
-
正如您在回答中提到的那样,当用户被添加到角色时,我正在尝试刷新用户角色。
-
这是一个非常相似的问题:stackoverflow.com/a/19354940/809357
标签: c# asp.net cookies asp.net-identity-2