简体   繁体   English

策略库授权 asp.net core 3.1

[英]Policy base authorization asp.net core 3.1

I want to authorize users in asp.net core 3.1 for example users that have admin role and CanDoSomething claim.我想授权 asp.net 核心 3.1 中的用户,例如具有管理员角色和CanDoSomething声明的用户。 I Remove AddDefaultIdentity and add pages that i need with scaffolding我删除 AddDefaultIdentity 并使用脚手架添加我需要的页面

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

Configure:配置:

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

Use it like this:像这样使用它:

 [Authorize(Policy = "superadmin")]
    public IActionResult Index()
    {
        return View();
    }

When i login it redirect me to access denied page I am doing it right?当我登录时,它会将我重定向到访问被拒绝的页面,我做得对吗? if yes What should i do now?如果是,我现在该怎么办?

I make some change and it worked but i dont know why我做了一些改变,它起作用了,但我不知道为什么

Remove ApplicationClaimsPrincipalFactory and add claim in Seed with AddClaimAsync删除ApplicationClaimsPrincipalFactory并使用 AddClaimAsync 在 Seed 中添加声明

In the first way when i check the db and table AspNetUserClaims there is no any CanDoSomething claim but i write this and problem solved:在第一种方式中,当我检查数据库和表AspNetUserClaims时,没有任何 CanDoSomething 声明,但我写了这个并解决了问题:

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

Why ApplicationClaimsPrincipalFactory not worked??为什么 ApplicationClaimsPrincipalFactory 不起作用?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 覆盖 ASP.NET Core 3 中的授权策略 - Override authorization policy in ASP.NET Core 3 在 ASP.NET Core 3.1 中处理多环境的 CORS 策略 - Handling CORS policy for multiple environment in ASP.NET Core 3.1 在 ASP.NET Core 3.1 中使用 windows 身份验证进行授权 - Authorization with windows authentication in ASP.NET Core 3.1 ASP.NET Core 3.1 的自定义身份验证处理程序的授权失败? - Authorization failing for custom authentication handler for ASP.NET Core 3.1? Swagger JWT 授权在 ASP.net 内核 3.1 中不起作用 - Swagger JWT Authorization does not work in ASP.net core 3.1 asp.net core 3.1+中多个中间件的认证和授权 - Authentication and authorization with multiple middlewares in asp.net core 3.1+ Asp.NET Core 3.1 中间件和授权处理程序订单 - Asp.NET Core 3.1 middleware’s and authorization handlers order Cookie身份验证不适用于asp.net核心中的授权策略 - Cookie Authentication not working with Authorization policy in asp.net core 从数据库加载 ASP.Net Core 授权策略 - Loading ASP.Net Core authorization policy from database 基于策略的授权不适用于asp.net核心 - Policy based Authorization not working in asp.net core
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM