我一直在尝试使用 .net8 提供的身份验证系统向我的 Web API 添加身份验证和授权,但我正在努力解决应该将用户添加到角色的部分,例如,当用户在我的应用程序中登录时,我想将该用户添加到客户端角色,如何才能做到这一点而无需重写整个注册方法?如果没有其他方法,我如何访问该方法来覆盖它?
这是我的代码,我是否遗漏了什么?
builder.Services.AddIdentityApiEndpoints<IdentityUser>(opt =>
{
opt.Password.RequiredLength = 8;
opt.User.RequireUniqueEmail = true;
opt.Password.RequireNonAlphanumeric = false;
opt.SignIn.RequireConfirmedEmail = true;
})
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
所以基本上我们需要在您的Program.cs
中将角色播种到我们的数据库中 using (var scope = app.Services.CreateScope())
{
var roleManager =
scope.ServiceProvider.GetRequiredService<RoleManager<IdentityRole>>();
string[] roles = new[] { "superuser", "Client" };
foreach (var role in roles)
{
if (!await roleManager.RoleExistsAsync(role))
{
await roleManager.CreateAsync(new IdentityRole(role));
}
确保您已在此处添加此内容,
builder.Services.AddScoped<UserManager<IdentityUser>, CustomUserManager<IdentityUser>>();
builder.Services.AddIdentityApiEndpoints<IdentityUser>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>();
builder.Services.AddScoped<UserManager<IdentityUser>, CustomUserManager<IdentityUser>>();
如果您在运行服务器后在数据库中看到,
新的我们需要分配默认角色,基本上默认情况下我们只能访问创建用户的链接,因此创建一个 C# 类名让我们说 CustomUserManager 和,
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Options;
namespace ReactApp2.Server.Services
{
public class CustomUserManager<TUser> : UserManager<TUser> where TUser : class
{
public CustomUserManager(IUserStore<TUser> store, IOptions<IdentityOptions> optionsAccessor, IPasswordHasher<TUser> passwordHasher,
IEnumerable<IUserValidator<TUser>> userValidators, IEnumerable<IPasswordValidator<TUser>> passwordValidators, ILookupNormalizer keyNormalizer,
IdentityErrorDescriber errors, IServiceProvider services, ILogger<UserManager<TUser>> logger)
: base(store, optionsAccessor, passwordHasher, userValidators, passwordValidators, keyNormalizer, errors, services, logger)
{
}
public override async Task<IdentityResult> CreateAsync(TUser user, string password)
{
var result = await base.CreateAsync(user, password);
if (result.Succeeded)
{
var defaultRole = "Client"; // Change to your default role name
await AddToRoleAsync(user, defaultRole);
}
return result;
}
}
}