我正在尝试使用 Identity and Entity Frame Work 向我的 ASPDotNet Core 项目添加管理员角色。 目标是让管理员能够访问 View / Controller ,从而允许他们对普通用户无法访问的网站进行更改。
这是我用来创建角色、 super 用户和数据库种子的代码(稍后我可能会制作一个种子数据库类,但我的重点是首先让基础知识发挥作用)。这段代码目前存在于我的启动类中。 CreateSuperUser 在配置方法中被调用。
private async Task CreateSuperUser(IServiceProvider serviceProvider)
{
var _roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var _userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();
IdentityResult result;
var doesAdminRoleExist = await _roleManager.RoleExistsAsync("AdminRole");
var doesBasicRoleExist = await _roleManager.RoleExistsAsync("BasicRole");
if (!doesAdminRoleExist)
{
IdentityRole AdminRole = new IdentityRole("AdminRole");
result = await _roleManager.CreateAsync(AdminRole);
IdentityUser SuperUser = new IdentityUser() { Email = "superuser@superuser.com", PasswordHash = "SecureP@ssword!1234", UserName = "superuser@superuser.com", };
var createSuperUser = await _userManager.CreateAsync(SuperUser, SuperUser.PasswordHash);
if (createSuperUser.Succeeded)
{
await _userManager.AddToRoleAsync(SuperUser, AdminRole.Name);
}
}
if (!doesBasicRoleExist)
{
IdentityRole BasicRole = new IdentityRole("BasicRole");
result = await _roleManager.CreateAsync(BasicRole);
}
}
在我的 Controller 类中,我请求这样的授权
[Authorize(Roles = "AdminRole")]
public IActionResult Contact()
{
ViewData["Message"] = "Your contact page.";
return View();
}
我可以通过 superUser@superuser.com 登录没有问题,但是当我尝试单击联系人链接时,它告诉我我无权访问此资源。 我根本不知道如何正确创建这个自定义角色。我的具体问题是: 谁能帮我找出我的流程中阻止我按角色授权的错误。
我花了很多时间阅读 stack overflow、google 和 Microsoft 文档,所以请不要建议。我的方法很大程度上基于此处对其他用户的回答之一,Microsoft 文档是我桌面上的 PDF。
我是编程新手,很难掌握这一切。特别是 2.0 和 2.1 的差异。更不用说 Framework 4.6 了。
我为这篇冗长的帖子道歉。预先感谢您的帮助。
附带说明一下,这里是我的配置方法,以备不时之需。我还从 nuget 的控制台运行了 add-migration/update-database。
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>();
services.AddAuthentication();
services.AddAuthorization();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider serviceProvider)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseDatabaseErrorPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseAuthentication();
CreateSuperUser(serviceProvider).Wait();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
最佳答案
这是一个被跟踪的错误 UserRoles in DefaultIdentity #1813 .
要变通,请像下面这样更改您的代码
//services.AddDefaultIdentity<IdentityUser>()
// .AddEntityFrameworkStores<ApplicationDbContext>();
//services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>()
// .AddEntityFrameworkStores<ApplicationDbContext>()
// ;
services.AddIdentity<IdentityUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultUI()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
此问题已在跟踪的 release/2.2
中修复 Fix issue with role claim missing in AddIdentityCore #1832 .
请注意,如果以上代码对您不起作用,您可能需要注销并登录,因为此身份由 Cookies
保存。
关于c# - 当被授权属性列为允许时,角色返回未授权,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51811104/