gpt4 book ai didi

c# - Asp Core 2.1 Jwt + 身份。 userManager 存储未实现 IUserRoleStore

转载 作者:行者123 更新时间:2023-11-30 21:32:34 30 4
gpt4 key购买 nike

我正在尝试在 ASP Net Core 2.1 中使用 Jwt 身份验证和身份

在我的 Startup.cs 中,我有:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.RequireHttpsMetadata = false;
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuer = true,
ValidIssuer = AuthOptions.ISSUER,
ValidateAudience = true,
ValidAudience = AuthOptions.AUDIENCE,
ValidateLifetime = true,
IssuerSigningKey = AuthOptions.GetSymmetricSecurityKey(),
ValidateIssuerSigningKey = true,
};
});

var builder = services.AddIdentityCore<User>(options =>
{
// Password settings
...
// Lockout settings
...
// User settings
options.User.RequireUniqueEmail = true;
}).AddEntityFrameworkStores<ApplicationDbContext>();

builder = new IdentityBuilder(builder.UserType, typeof(IdentityRole), builder.Services);

然后在 SecurityService.cs 中我尝试使用此语句获取角色

var roles = await _userManager.GetRolesAsync(user);

并且它抛出以下异常:

NotSupportedException: Store does not implement IUserRoleStore
Microsoft.AspNetCore.Identity.UserManager.GetUserRoleStore()

我找到它是因为AddIdentityCore : 如果我用 AddIdentity<User, IdentityRole>相反它有效,但是然后 [Authorize]不起作用

有人遇到过类似的情况吗?或者为什么会发生这种情况?

最佳答案

当您使用AddIdentity<TUser, TRole>时,该调用配置默认身份验证方案,如下所示 ( source ):

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})

在您的 Startup.ConfigureServices 中,您有以下内容,设置默认身份验证方案:

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)

由于定义的顺序( AddIdentityafter AddAuthentication ),默认值从 Jwt 更改为 Identity,因此当您使用 [Authorize] 时,身份验证过程现在期望使用 Identity 而不是 Jwt。

要解决此问题,最简单的选择是切换 AddIdentity 的顺序和AddAuthentication ,因此 JwtBearer 调用最后出现,因此“获胜”。您还需要更明确地设置 DefaultAuthenticateSchemeDefaultChallengeScheme :

services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(...);

另一种选择是在 [Authorize] 中明确显示属性,调用您要使用的哪种身份验证方案,例如以下两行之一:

[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = IdentityConstants.ApplicationScheme)]

似乎第一个选项最适合您的用例,但很高兴知道第二个选项存在,如果您在进一步使用身份时需要它(还有更多 - 例如使用策略)。

关于c# - Asp Core 2.1 Jwt + 身份。 userManager 存储未实现 IUserRoleStore,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52206742/

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