【问题标题】:Policy base authorization asp.net core 3.1策略库授权 asp.net core 3.1
【发布时间】:2020-04-09 14:19:39
【问题描述】:

我想在 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;
    }
}

配置服务:

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

当我登录时,它会将我重定向到访问被拒绝的页面 我做得对吗?如果是,我现在该怎么办?

【问题讨论】:

  • 如果您使用角色 admin 和 Candosomthing 声明登录,您可以成功访问索引。但它重定向到访问拒绝页面,这意味着您没有正确的角色或声明。所以,您使用角色是否正确?您是如何为您的用户添加角色的?您能分享更多代码吗?
  • @Rena Ty 请注意,我编辑了我的帖子并添加了 ApplicationDbInitializer,我写了这个角色创建并且用户成功添加到角色,当我检查数据库时它没问题,我让 @987654326 @ 该用户

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


【解决方案1】:

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

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

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

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

为什么 ApplicationClaimsPrincipalFactory 不起作用??

【讨论】: