策略库授权asp.net core 3.1

时间:2020-04-08 13:54:39

标签: asp.net-core asp.net-identity

我想授权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();
    }

我登录时将其重定向到拒绝访问页面 我做对了吗?如果是,我现在应该怎么办?

1 个答案:

答案 0 :(得分:0)

我做了一些更改,它有效,但我不知道为什么

删除 ApplicationClaimsPrincipalFactory 并使用AddClaimAsync在Seed中添加声明

当我检查数据库和表 AspNetUserClaims 的第一种方式时,没有任何CanDoSomething声明,但是我写了这个并解决了问题:

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

为什么ApplicationClaimsPrincipalFactory无法正常工作?