当我想给用户添加角色时,我得到了这个。
存储未实现IUserRoleStore。
如何解决此错误?
我使用了. NET 7
。
public static async Task SeedUsersAsync(UserManager<ApplicationUser> userManager)
{
if (!userManager.Users.Any())
{
var user = new ApplicationUser
{
DisplayName = "Bob",
Email = "bob@test.com",
UserName = "bob@test.com",
Address = new Address
{
FirstName = "Bob",
LastName = "Bobbity",
Street = "10 The street",
City = "New York",
State = "NY",
ZipCode = "90210"
},
EmailConfirmed = true,
};
await userManager.CreateAsync(user, "Pa$$w0rd");
await userManager.AddToRoleAsync(user, Roles.Standard.ToString("f")); // Error happend here!
}
}
身份服务扩展:
public static class IdentityServiceExtensions
{
public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
{
var builder = services.AddIdentityCore<ApplicationUser>();
builder = new IdentityBuilder(builder.UserType, builder.Services);
builder.AddEntityFrameworkStores<ShopDbContext>();
builder.AddSignInManager<SignInManager<ApplicationUser>>();
builder.Services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ShopDbContext>();
services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
.AddJwtBearer(options =>
{
options.TokenValidationParameters = new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
ValidIssuer = config["Token:Issuer"],
ValidateIssuer = true,
ValidateAudience = false
};
});
services.AddAuthorization(opts =>
{
opts.AddPolicy(PolicyType.RequireSuperAdminRole.ToString("f"), policy => policy.RequireRole("SuperAdmin"));
opts.AddPolicy(PolicyType.RequireAdministratorRole.ToString("f"), policy => policy.RequireRole("Admin", "SuperAdmin"));
opts.AddPolicy(PolicyType.RequireStandardRole.ToString("f"), policy => policy.RequireRole("Basic", "Admin", "SuperAdmin"));
});
return services;
}
}
Program.cs:
using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider;
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
try
{
var context = services.GetRequiredService<ShopDbContext>();
var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();
await context.Database.MigrateAsync();
await ShopContextSeed.SeedAsync(context, loggerFactory);
await IdentityContextSeed.SeedRolesAsync(roleManager);
await IdentityContextSeed.SeedUsersAsync(userManager);
}
catch (Exception ex)
{
var logger = loggerFactory.CreateLogger<Program>();
logger.LogError(ex, "An error occurred during migration");
}
1条答案
按热度按时间eagi6jfj1#
我添加了
builder.AddRoles<ApplicationRole>()
并删除了builder.Services.AddIdentity
。