核心 2.0,使用 AspnetCore.Identity。我创建了一些角色,包括“管理员”。
//initializing custom roles
var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
string[] roleNames = { "Admin", "Training", "Operations", "Membership", "Individual" };
IdentityResult roleResult;
foreach (var roleName in roleNames)
{
var roleExist = await RoleManager.RoleExistsAsync(roleName);
// ensure that the role does not exist
if (!roleExist)
{
//create the roles and seed them to the database:
roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));
}
}
我检查了 SQL 表,它们都在那里。:
然后我将自己添加到 Admin 角色(不是完整方法,而是相关部分):
var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
var _eric = await UserManager.FindByEmailAsync("username@gmail.com");
await UserManager.AddToRoleAsync(_eric, "Admin");
我检查了表格,然后我在那里(与我添加到不同角色的另一个人一起):
然后我转到我的方法并使用两个角色对其进行授权,其中一个角色是(管理员):
[Authorize(Roles ="Training, Admin")]
public ActionResult Index()
{
return View();
}
然后我得到 访问被拒绝 .我错过了一些东西,但无法弄清楚我搞砸了哪一步。用户在那里,我已登录,数据表显示我已分配角色,并且授权标记看起来不错。
最佳答案
角色是声明,声明仅在登录时加载。如果您修改声明(例如通过添加角色),您必须注销用户并自动将其重新登录或提示用户重新进行身份验证,重新加载 claim 。
关于security - aspnetcore.identity - 在角色中,但被拒绝访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49259980/