我正在使用ASP.NET MVC 5和Identity 2与Entity Framework 6的系统.当用户登录时,我向该登录会话添加一些声明.我不想使用索赔表.
对于我的一个主张,我确实喜欢这样:
public class User : IdentityUser<int, UserLogin, UserRole, UserClaim>
{
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<User, int> manager)
{
// Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
//We add the display name so that the _LoginPartial can pick it up;
userIdentity.AddClaim(new Claim("DisplayName", FirstName + " " + LastName));
// Add custom user claims here
return userIdentity;
}
public virtual ICollection<UserInsurance> UserInsurances { get; set; }
public User() …Run Code Online (Sandbox Code Playgroud) asp.net-mvc login claims asp.net-identity asp.net-identity-2
我看到一个几年前就已经被问过的问题,它解释了与使用 AspNet Identity 时丢失自定义声明相关的问题。不幸的是,那里提到的解决方案对我不起作用,因为我在 .NET 6 Blazor Server 应用程序上使用 AspNet Core Identity。
问题是类似的(在下面几点解释):
我在登录期间添加了一些声明(这些声明来自某些 API 调用,而不是来自 Identity 数据库,因此我在登录期间添加它们)。
我可以从 Blazor 组件访问它们。
它在 30% 的情况下工作正常,但在 70% 的情况下,cookie 会丢失我在登录期间添加的自定义声明,并且我的应用程序会遇到问题。我什至无法弄清楚这些声明何时会丢失,因为在这两种情况下都没有发生这种情况,RevalidationInterval因为我用 1 分钟的时间跨度对其进行了测试,并且当我多次测试它时,它至少在 5 分钟内运行良好。搜索了一堆答案,但没有找到 AspNet Core Identity 的正确答案。
这就是我的代码的样子:
builder.Services
.AddDefaultIdentity<IdentityUser>(options =>
{
options.SignIn.RequireConfirmedAccount = false;
// Set Password options here if you'd like:
options.Password.RequiredLength = 6;
})
.AddRoles<IdentityRole>()
.AddUserManager<ADUserManager<IdentityUser>>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddScoped<AuthenticationStateProvider, RevalidatingIdentityAuthenticationStateProvider<ApplicationUser>>();
Run Code Online (Sandbox Code Playgroud)
public async Task<IActionResult> OnPostAsync(string returnUrl = null)
{
returnUrl ??= Url.Content("~/"); …Run Code Online (Sandbox Code Playgroud) c# asp.net-identity asp.net-core blazor-server-side .net-6.0