Я хочу авторизовать пользователей в asp. net core 3.1, например, пользователей, которые имеют admin роль и CanDoSomething претензию. Я удаляю AddDefaultIdentity и добавляю нужные мне страницы с помощью скаффолдинга
ApplicationClaimsPrincipalFactory:
public class ApplicationClaimsPrincipalFactory : UserClaimsPrincipalFactory<ApplicationUser>
{
public ApplicationClaimsPrincipalFactory(
UserManager<ApplicationUser> userManager,
IOptions<IdentityOptions> optionsAccessor) : base(userManager, optionsAccessor)
{ }
public override async Task<ClaimsPrincipal> CreateAsync(ApplicationUser user)
{
var principal = await base.CreateAsync(user);
if (user.CanDoSomething) //it's true
{
((ClaimsIdentity)principal.Identity)
.AddClaim(new Claim("CanDoSomething", "true"));
}
return principal;
}
}
ConfigureServices:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddControllersWithViews();
services.AddRazorPages();
services.AddMvc();
services.AddAuthorization(options =>
{
options.AddPolicy("superadmin", policy =>
policy
.RequireRole("admin")
.RequireClaim("CanDoSomething", "true"));
});
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, ApplicationClaimsPrincipalFactory>();
}
Настройка:
public void Configure(
IApplicationBuilder app,
IWebHostEnvironment env,
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
endpoints.MapRazorPages();
});
ApplicationDbInitializer.Seed(userManager, roleManager);//Role created and users add to role successfully
}
ApplicationDbInitializer:
public static class ApplicationDbInitializer
{
public static void Seed(
UserManager<ApplicationUser> userManager,
RoleManager<IdentityRole> roleManager)
{
var roleName = "admin";
var pw = "@Vv123456";
roleManager.CreateAsync(new IdentityRole
{
Name = roleName,
NormalizedName = roleName.ToUpper()
}).Wait();
if (userManager.FindByEmailAsync("b@b.com").Result == null)
{
var user = new ApplicationUser
{
UserName = "b@b.com",
Email = "b@b.com",
CanDoSomething = true
};
if (userManager.CreateAsync(user, pw).Result.Succeeded)
userManager.AddToRoleAsync(user, roleName).Wait();
}
}
}
Используйте это так:
[Authorize(Policy = "superadmin")]
public IActionResult Index()
{
return View();
}
Когда я захожу, он перенаправляет меня на страницу с отказом в доступе. Я правильно делаю? если да Что мне теперь делать?