簡體   English   中英

策略庫授權 asp.net core 3.1

[英]Policy base authorization asp.net core 3.1

我想授權 asp.net 核心 3.1 中的用戶,例如具有管理員角色和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;
    }
}

配置服務:

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();
    }

當我登錄時,它會將我重定向到訪問被拒絕的頁面,我做得對嗎? 如果是,我現在該怎么辦?

我做了一些改變,它起作用了,但我不知道為什么

刪除ApplicationClaimsPrincipalFactory並使用 AddClaimAsync 在 Seed 中添加聲明

在第一種方式中,當我檢查數據庫和表AspNetUserClaims時,沒有任何 CanDoSomething 聲明,但我寫了這個並解決了問題:

userManager.AddClaimAsync(user, new Claim(CanDoSomething, "true")).Wait();

為什么 ApplicationClaimsPrincipalFactory 不起作用?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM