简体   繁体   English

如何在ASP.NET Core中修复基于策略的授权

[英]How to fix policy based authorization in ASP.NET Core

I'm trying to implement a policy based authorization on my Movies controller to only allow access for an Admin user. 我试图在我的电影控制器上实施基于策略的授权,以仅允许管理员用户访问。

I added an authorization policy "CanManageMovies" and assigned it to the Admin role. 我添加了一个授权策略“ CanManageMovies”,并将其分配给管理员角色。 Then, I added the policy to my Movies controller. 然后,将策略添加到我的电影控制器。 I seeded the Admin role and user in my Db. 我在db中植入了Admin角色和用户。

// Authorization policy in Startup.cs ConfigureServices method

services.AddAuthorization(options =>
            {
                options.AddPolicy("CanManageMovies",
                    policy => policy.RequireRole("Admin"));
            });
// Movies controller

[Authorize(Policy = "CanManageMovies")]
    public class MoviesController : Controller
    {
      // code removed for brevity
    }
// This seeds the admin user and role. 
// The SeedData method is called in the Startup configure method. 

public class MyIdentityDbInitializer
    {
        public static void SeedData(UserManager<IdentityUser> userManager,
            RoleManager<IdentityRole> roleManager)
        {
            SeedRoles(roleManager);
            SeedUsers(userManager);
        }

        public static void SeedUsers(UserManager<IdentityUser> userManager)
        {
            if (userManager.FindByNameAsync
                ("user@vidly.com").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "user@vidly.com";
                user.Email = "user1@localhost";

                IdentityResult result = userManager.CreateAsync
                (user, "Password#1").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "User").Wait();
                }
            }

            if (userManager.FindByNameAsync
            ("admin@vidly.com").Result == null)
            {
                IdentityUser user = new IdentityUser();
                user.UserName = "admin@vidly.com";
                user.Email = "admin@vidly.com";

                IdentityResult result = userManager.CreateAsync
                (user, "Password#1").Result;

                if (result.Succeeded)
                {
                    userManager.AddToRoleAsync(user,
                                        "Admin").Wait();
                }
            }
        }

        public static void SeedRoles(RoleManager<IdentityRole> roleManager)
        {
            if (!roleManager.RoleExistsAsync("User").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "User";
                IdentityResult roleResult = roleManager.
                CreateAsync(role).Result;
            }


            if (!roleManager.RoleExistsAsync
            ("Admin").Result)
            {
                IdentityRole role = new IdentityRole();
                role.Name = "Admin";
                IdentityResult roleResult = roleManager.
                CreateAsync(role).Result;
            }
        }
    }

When I run the app, navigate to Movies, and login with the Admin user, I expect to access the view, but I receive a "Not Authorized" message. 当我运行该应用程序,导航至“电影”并使用Admin用户登录时,我希望访问该视图,但会收到“未授权”消息。

Check if the ConfigureServices method and the Configure method in Startup.cs like below: 检查Startup.cs中的ConfigureServices方法和Configure方法是否如下所示:

 public void ConfigureServices(IServiceCollection services)
    {
        services.Configure<CookiePolicyOptions>(options =>
        {
            // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            options.CheckConsentNeeded = context => true;
            options.MinimumSameSitePolicy = SameSiteMode.None;
        });

        services.AddDbContext<ApplicationDbContext>(options =>
            options.UseSqlServer(
                Configuration.GetConnectionString("DefaultConnection")));
        services.AddDefaultIdentity<IdentityUser>()
            .AddRoles<IdentityRole>()
            .AddDefaultUI(UIFramework.Bootstrap4)
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        services.AddAuthorization(options =>
        {
            options.AddPolicy("CanManageMovies",
                policy => policy.RequireRole("Admin"));
        });
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, IServiceProvider serviceProvider, UserManager<IdentityUser> 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.UseCookiePolicy();

        app.UseAuthentication();
        MyIdentityDbInitializer.SeedData(userManager, roleManager);

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
    }

Here is a simple working demo , you could refer to and check the difference . 是一个简单的工作演示,您可以参考并检查其区别。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM