简体   繁体   English

如何检查登录用户是否在 ASP.NET Core 中扮演角色

[英]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:我有两个角色:

  • The Manager "CanManage" (CRUD)经理“CanManage”(增删改查)
  • The User "CanUse"用户“可以使用”
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?每次boolfalse时,知道如何检查用户角色吗?

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.必须执行几个步骤才能用声明替换角色。

  1. Prepopulate the database with claims and users, inside the 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" });
}
  1. Drop-Database in the Package Manager Console (PMC) to start fresh在 Package 管理器控制台 (PMC) 中Drop-Database以重新开始
  2. Add-Migration Claims , then Update-Database Add-Migration Claims ,然后Update-Database
  3. An extra class just to reference the names of the claims and policies一个额外的 class 只是为了参考索赔和保单的名称
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";
}
  1. In the Program.cs made a policyProgram.cs中做了一个policy
builder.Services.AddAuthorization(options => {
    options.AddPolicy(AppPolicyName.Management,
        policy => policy.RequireClaim(AppClaimType.Manage, "true"));
});
  1. Finally do the check in the Controller最后在 Controller 检查
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.

相关问题 检查用户是否在 ASP.NET Core 中登录 - Check if user is logged on in ASP.NET Core 如何检查用户是否在 Asp.Net Core Identity Framework 中担任角色 - How to check if a user is in a role in Asp.Net Core Identity Framework 如何在 ASP.NET Core 中以编程方式检查用户是否处于角色中? - How to check that user is in a role programmatically in ASP.NET Core? ASP.NET 核心 Web API - 如何 ZE0626222614BDEE31951D84C64E5E 使用基于登录用户角色的 DBEE31951D84C64E5E 身份登录用户角色 - ASP.NET Core Web API - How to Select Records based on logged in user role using DB Identity 检查用户是否使用ASP.NET Core中的基于令牌的身份验证登录 - Check if user is logged in with Token Based Authentication in ASP.NET Core ASP.NET身份-如何维护登录用户角色? - Asp.net identity - How to maintain logged in user role? 如何检查用户是否重新登录并访问 ASP.NET Core Web API 中的相同 API - How to check if a user re-logged in and accessing the same API in ASP.NET Core Web API 在ASP.NET Core 2.1中,如何在用户基于角色登录后添加菜单项? - In ASP.NET Core 2.1 how do I add menu items after the user has logged in based on Role? ASP.NET Core-如何获取当前登录的用户 - ASP.NET Core - How to get currently logged in user 获取ASP.NET Core MVC中当前登录用户的角色 - Get role/s of current logged in user in ASP.NET Core MVC
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM