[英]ASP.NET Core 2.1: Razor Pages - role based authorisation not working
[英]How to create a claim based authorisation system implemented using role names? ASP.NET Core 2.1
在我的應用程序中,我已經將用戶以及一些數據植入到我的應用程序中,但現在我正在嘗試創建一個系統,我可以在其中為用戶分配角色。 我認為這可以通過使用 ASP.NET Identity 中的聲明系統或使用角色名稱的基於聲明的授權系統來實現,我對采用哪種方法以及如何到達那里感到有些困惑。
目前,我已經創建了一種為用戶和聯系人提供種子的方法,但我閱讀了有關RoleManager<IdentityRole>
,我認為這是正確的方法,但我也不確定。
public static class DbInit
{
public static void SeedDb(ApplicationDbContext context, UserManager<IdentityUser> userManager, RoleManager<IdentityRole> roleManager)
{
SeedPosts(context);
SeedUsers(userManager);
}
private static void SeedUsers(UserManager<IdentityUser> userManager)
{
IdentityUser user = new IdentityUser
{
UserName = "Member1@email.com",
Email = "Member1@email.com"
};
userManager.CreateAsync(user, "Password123!").Wait();
}
private static void SeedContacts(ApplicationDbContext context)
{
context.Database.EnsureCreated();
context.Contact.Add(
new Contact() { }
);
context.SaveChanges();
}
}
要創建角色,請嘗試
var userRole = await _roleManager.CreateAsync(new IdentityRole("User"));
要為角色分配聲明,請嘗試
var role = await _roleManager.FindByNameAsync("User");
var roleClaims = await _roleManager.AddClaimAsync(role, new Claim("area", "public1"));
要向用戶添加角色,請嘗試
var user = await _userManager.FindByNameAsync(User.Identity.Name);
var roleToUser = await _userManager.AddToRoleAsync(user, "User");
看來你沒有定義異步方法,你可以試試_userManager.AddToRoleAsync(user, "User").Wait()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.