[英]How to check if a logged in user is in a role in ASP.NET Core
Hello I'm somehow new in ASP.NET Core, I want to check, in the controller, if a logged-in user is in a certain role, to return the appropriate view.您好,我是 ASP.NET Core 的新手,我想在 controller 中检查登录用户是否处于特定角色,以返回适当的视图。 One view with the CRUD links, the other read-only.
一个带有 CRUD 链接的视图,另一个是只读的。
I have two roles:我有两个角色:
public async Task<IActionResult> Index() {
bool isInrole = User.IsInRole("CanManage"); // First try
bool isInrole = HttpContext.User.IsInRole("CanManage"); // Second try
bool isInrole = User.HasClaim(ClaimTypes.Role, "CanManage"); // Third try
if (isInrole)
return View(await _context.Etudiants.ToListAsync());
return View("IndexReadonly", await _context.Etudiants.ToListAsync());
}
Each time the bool
is false
, any idea how to check the user roles?每次
bool
为false
时,知道如何检查用户角色吗?
Finally, I found a solution.最后,我找到了解决方案。
After some readings, it has been said that the Roles are somehow old school, and the Claims are the actual way.经过一些阅读,有人说 Roles 在某种程度上是老派的,而 Claims 是实际的方式。 (If it makes sense...)
(如果有道理……)
So, I did.所以我做了。
Had to do few steps to replace roles with claims.必须执行几个步骤才能用声明替换角色。
ApplicationDBContext
class, in the OnModelCreating
methodApplicationDBContext
class 中的OnModelCreating
方法中使用声明和用户预填充数据库protected override void OnModelCreating(ModelBuilder modelBuilder) {
// Fluent API
//...
string MANAGER_ID = Guid.NewGuid().ToString();
string BASIC_ID = Guid.NewGuid().ToString();
var passwordHasher = new PasswordHasher<IdentityUser>();
// Manager
var managerName = "manager@email.com";
var manager = new IdentityUser {
Id = MANAGER_ID, // Primary key
Email = managerName,
NormalizedEmail = managerName.ToUpper(),
UserName = managerName,
NormalizedUserName = managerName.ToUpper(),
EmailConfirmed = true,
};
manager.PasswordHash = passwordHasher.HashPassword(manager, "Pass_12345");
// Basic user
var basicname = "basic@email.com";
var basic = new IdentityUser {
Id = BASIC_ID, // Primary key
Email = basicname,
NormalizedEmail = basicname.ToUpper(),
UserName = basicname,
NormalizedUserName = basicname.ToUpper(),
EmailConfirmed = true,
};
basic.PasswordHash = passwordHasher.HashPassword(basic, "Pass_12345");
// Seeding the User to AspNetUsers table
builder.Entity<IdentityUser>().HasData(manager, basic);
builder.Entity<IdentityUserClaim<string>>().HasData(
new IdentityUserClaim<string> { Id = 1, UserId = MANAGER_ID, ClaimType = AppClaimType.Manage, ClaimValue = "true" },
new IdentityUserClaim<string> { Id = 2, UserId = BASIC_ID, ClaimType = AppClaimType.Basic, ClaimValue = "true" });
}
Drop-Database
in the Package Manager Console (PMC) to start freshDrop-Database
以重新开始Add-Migration Claims
, then Update-Database
Add-Migration Claims
,然后Update-Database
public class AppClaimType{
public const string Manage = "Manage Role";
public const string Basic = "Basic Role";
}
public class AppPolicyName{
public const string Management = "Management";
public const string BasicUsage = "BasicUsage";
}
Program.cs
made a policyProgram.cs
中做了一个policybuilder.Services.AddAuthorization(options => {
options.AddPolicy(AppPolicyName.Management,
policy => policy.RequireClaim(AppClaimType.Manage, "true"));
});
public async Task<IActionResult> Index() {
bool hasClaim = User.HasClaim(AppClaimType.Manage, "true");
if (hasClaim)
return View(await _context.Etudiants.ToListAsync());
return View("IndexReadonly", await _context.Etudiants.ToListAsync());
}
Now the bool
gets the correct value as expected, depends on the logged-in user (basic or manager)现在
bool
获得了预期的正确值,具体取决于登录用户(基本用户或管理员)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.