gpt4 book ai didi

asp.net - HttpContext.Current 在 RegenerateIdentity 期间为空

转载 作者:行者123 更新时间:2023-12-02 04:52:03 24 4
gpt4 key购买 nike

简介:

我正在构建 Identity 2.0 的自定义实现。默认情况下,框架每 30 分钟刷新一次用户身份,创建一个新的 ClaimsIdentity。因为我有一些自定义声明(我在登录方法中设置),我想在刷新时移至新的 ClaimsIdentity,所以我想出了一种读取当前 ClaimsIdentity< 的方法 来自 HttpContext 并将其作为"new"ClaimsIdentity 返回。问题是 HttpContext.Current 在刷新身份时为 null,因此我无法将旧声明复制到新身份。

代码:

在我的 Startup.cs 文件中,我有这段代码每 x 分钟刷新一次用户的身份:

app.UseCookieAuthentication(new CookieAuthenticationOptions
{
AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
Provider = new CookieAuthenticationProvider
{
OnValidateIdentity = SecurityStampValidatorExtensions.OnValidateIdentity(
validateInterval: TimeSpan.FromMinutes(0.5),
regenerateIdentity: (manager, user) => manager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie))
}
});

RegenerateIdentity 函数在我的 UserManager 中调用此方法:

public async override Task<ClaimsIdentity> CreateIdentityAsync(ApplicationUser user, string authenticationType)
{
ClaimsIdentity claimsIdentity;
if (HttpContext.Current != null &&
HttpContext.Current.User != null &&
HttpContext.Current.User.Identity != null &&
HttpContext.Current.User.Identity.IsAuthenticated)
{
// Just return the existing ClaimsIdentity so we don't lose our custom claims
claimsIdentity = (ClaimsIdentity)HttpContext.Current.User.Identity;

// TODO refresh some claims from the database

return claimsIdentity;
}

// Create a new ClaimsIdentity if none exists
claimsIdentity = await ClaimsIdentityFactory.CreateAsync(this, user, authenticationType);
claimsIdentity.AddClaim(new Claim(Constants.DefaultSecurityStampClaimType, await GetSecurityStampAsync(user.Id)));

return claimsIdentity;
}

问题:

第一次 CreateIdentityAsync 被调用(当我登录时),HttpContext.Current 有一个值,身份被创建,一切都很好。问题是:再次调用 CreateIdentityAsync 时(因为正在刷新身份),HttpContext.Currentnull。我不明白为什么会这样,而且我无法修复它。

理论:

我关于为什么 HttpContext.Currentnull 的一些理论:

  1. 与异步和 HttpContext 没有被转移到新线程有关吗?我尝试构建自己的等待程序以复制 HttpContext.Current,但这没有用。
  2. HttpContext 正在被框架主动销毁以确保它摆脱一切?我还没有找到任何执行此操作的代码,所以这似乎不太可能。

有没有人对如何实现这一目标有任何建议?

最佳答案

cookie 中间件在 IIS 管道中的身份验证阶段运行,该阶段在 HttpContext 或 session 状态可用之前。所以你需要在没有它的情况下工作。

关于asp.net - HttpContext.Current 在 RegenerateIdentity 期间为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27270214/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com