我试图在我的Movies控制器上实施基于策略的授权,以仅允许Admin用户访问。
我添加了一个授权策略“ CanManageMovies”,并将其分配给管理员角色。然后,将策略添加到我的电影控制器。我在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;
}
}
}
当我运行该应用程序时,导航至“电影”,然后以Admin用户身份登录,我希望访问该视图,但会收到“未授权”消息。
答案 0 :(得分:0)
检查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是一个简单的工作演示,您可以参考并检查其区别。