![](/img/trans.png)
[英]Store does not implement IUserRoleStore<TUser> ASP.NET Core Identity
[英]Asp Core 2.1 Jwt + Identity. userManager store does not implement IUserRoleStore
我正在嘗試在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 =新的IdentityBuilder(builder.UserType,typeof(IdentityRole),builder.Services);
然后在SecurityService.cs中,我嘗試使用此語句來獲取角色
var roles = await _userManager.GetRolesAsync(user);
並拋出以下異常:
NotSupportedException:存儲未實現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)
由於已定義順序( AddIdentity
在 AddAuthentication
之后 ),因此默認值是從Jwt更改為Identity,因此當您使用[Authorize]
,身份驗證過程現在期望使用Identity而不是Jwt。
要解決此問題,最簡單的選擇是切換AddIdentity
和AddAuthentication
的順序,因此JwtBearer調用排在最后,因此“獲勝”。 您還需要更加明確,並同時設置DefaultAuthenticateScheme
和DefaultChallengeScheme
:
services.AddAuthentication(options =>
{
options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
})
.AddJwtBearer(...);
另一種選擇是是明確的[Authorize]
屬性,呼喚你想使用,像下面的兩個線中的哪認證方案:
[Authorize(AuthenticationSchemes = JwtBearerDefaults.AuthenticationScheme)]
[Authorize(AuthenticationSchemes = IdentityConstants.ApplicationScheme)]
似乎第一種選擇最適合您的用例,但是很高興知道,當您進一步使用Identity時(如果有更多選擇,例如使用策略),如果您需要第二種選擇,則可以使用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.