我正在使用 ASP.NET Core 2.1和.NET的新身份框架。只要不请求特定于角色的角色,常规Authorization
属性就会起作用。
是否需要一些扩展/自定义策略才能使用角色?下面是我的代码的最小化示例:
启动.cs
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>()
.AddEntityFrameworkStores<ApplicationDbContext>();
// Does not change anything
// services.AddAuthorization();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
首页控制器.cs
public async Task<IActionResult> Index()
{
if (!await _roleManager.RoleExistsAsync("Admin"))
{
await _roleManager.CreateAsync(new IdentityRole("Admin"));
}
var user = await _userManager.FindByEmailAsync("danny.meier@tpcag.ch");
if (!await _userManager.IsInRoleAsync(user, "Admin"))
{
await _userManager.AddToRoleAsync(user, "Admin");
await _userManager.UpdateAsync(user);
}
return View();
}
[Authorize]
public IActionResult About()
{
ViewData["Message"] = "Your application description page.";
return View();
}
[Authorize(Roles = "Admin")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
这是2.1
版本中的已知问题,已在2.2 preview-1
中修复。
原因是ASP.NET Core 2.1
年引入的新AddDefaultIdentity<TUser>()
方法默认情况下不会启用Roles
。
绕开它,与其使用新AddDefaultIdentity<TUser>()
来配置Identity,不如使用旧式的api:
services.AddIdentity<AppUser, IdentityRole>()
.AddRoleManager<RoleManager<IdentityRole>>()
.AddDefaultUI()
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();
另外,如果您之前已经登录过某人,请先注销并再次登录,它现在将按预期工作。
[编辑]对于 ASP.NET 核心3.1,调用.AddRoles<IdentityRole>()
:
services.AddDefaultIdentity<IdentityUser>(options => options.SignIn.RequireConfirmedAccount = true)
.AddRoles<IdentityRole>()
.AddEntityFrameworkStores<AppIdentityDbContext>();
然后注销并再次登录。
嗯。我在正在运行的 Asp.Net 2.1 项目中有以下代码:
services.AddDefaultIdentity<IdentityUser>()
.AddRoles<IdentityRole>()
//.AddDefaultUI(UIFramework.Bootstrap4)
.AddDefaultTokenProviders()
.AddEntityFrameworkStores<ApplicationDbContext>();