ASP.NET 核心身份 2:User.IsInRole 总是 returns 错误

ASP.NET Core Identity 2: User.IsInRole always returns false

问题:我调用RoleManager.CreateAsync()RoleManager.AddClaimAsync()来创建角色和关联的角色声明。然后我调用 UserManager.AddToRoleAsync() 将用户添加到这些角色。但是当用户登录时,角色和关联的声明都不会出现在 ClaimsPrincipal(即控制器的 User 对象)中。这样做的结果是 User.IsInRole() 总是 returns false,并且 User.Claims 返回的声明集合不包含角色声明,并且 [Authorize(policy: xxx)] 注释不工作。

我还应该补充一点,一种解决方案是从使用新的 services.AddDefaultIdentity()(由模板代码提供)恢复到调用 services.AddIdentity().AddSomething().AddSomethingElse()。我不想去那里,因为我在网上看到太多相互矛盾的故事,关于我需要做什么来为各种用例配置 AddIdentityAddDefaultIdentity 似乎无需大量添加流畅的配置即可正确完成大多数事情。

顺便说一句,我问这个问题的目的是回答它...除非其他人给我的答案比我准备好的答案更好post。我也在问这个问题,因为 经过几周的搜索,我还没有找到在 ASP.NET Core Identity 2[=96 中创建和使用角色和声明的良好端到端示例=].希望这个问题中的代码示例可以帮助其他偶然发现它的人...

设置: 我创建了一个新的 ASP.NET 核心 Web 应用程序,select Web 应用程序(模型-视图-控制器),并将身份验证更改为个人用户帐户。在生成的项目中,我执行以下操作:

  • 在程序包管理器控制台中,更新数据库以匹配脚手架迁移:

    update-database

  • 添加扩展 IdentityUserApplicationUser class。这涉及添加 class,向 ApplicationDbContext 添加一行代码,并在项目的任何地方将 <IdentityUser> 的每个实例替换为 <ApplicationUser>

    ApplicationUserclass:

    public class ApplicationUser : IdentityUser
    {
        public string FullName { get; set; }
    }
    

    更新后ApplicationDbContextclass:

    public class ApplicationDbContext : IdentityDbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
            : base(options)
        { }
    
        // Add this line of code
        public DbSet<ApplicationUser> ApplicationUsers { get; set; }
    }
    
  • 在程序包管理器控制台中,创建新的迁移并更新数据库以合并 ApplicationUsers 实体。

    add-migration m_001
    update-database

  • Startup.cs中添加下面一行代码来启用RoleManager

    services.AddDefaultIdentity<ApplicationUser>()
        .AddRoles<IdentityRole>() // <-- Add this line
        .AddEntityFrameworkStores<ApplicationDbContext>();
    
  • 为种子角色、声明和用户添加一些代码。此示例代码的基本概念是我有两个声明:can_report 允许持有人创建报告,can_test 允许持有人进行 运行 测试。我有两个角色,AdminTesterTester 角色可以 运行 测试,但不能创建报告。 Admin 角色可以做到这两点。因此,我将声明添加到角色,并创建了一个 Admin 测试用户和一个 Tester 测试用户。

    首先,我添加一个 class,其唯一目的是包含此示例中其他地方使用的常量:

    // Contains constant strings used throughout this example
    public class MyApp
    {
        // Claims
        public const string CanTestClaim = "can_test";
        public const string CanReportClaim = "can_report";
    
        // Role names
        public const string AdminRole = "admin";
        public const string TesterRole = "tester";
    
        // Authorization policy names
        public const string CanTestPolicy = "can_test";
        public const string CanReportPolicy = "can_report";
    }
    

    接下来,我为我的角色、声明和用户设定种子。为了方便起见,我将这段代码放在主登陆页面控制器中;它确实属于 "startup" Configure 方法,但那是额外的六行代码...

    public class HomeController : Controller
    {
        const string Password = "QwertyA1?";
    
        const string AdminEmail = "admin@example.com";
        const string TesterEmail = "tester@example.com";
    
        private readonly RoleManager<IdentityRole> _roleManager;
        private readonly UserManager<ApplicationUser> _userManager;
    
        // Constructor (DI claptrap)
        public HomeController(RoleManager<IdentityRole> roleManager, UserManager<ApplicationUser> userManager)
        {
            _roleManager = roleManager;
            _userManager = userManager;
        }
    
        public async Task<IActionResult> Index()
        {
            // Initialize roles
            if (!await _roleManager.RoleExistsAsync(MyApp.AdminRole)) {
                var role = new IdentityRole(MyApp.AdminRole);
                await _roleManager.CreateAsync(role);
                await _roleManager.AddClaimAsync(role, new Claim(MyApp.CanTestClaim, ""));
                await _roleManager.AddClaimAsync(role, new Claim(MyApp.CanReportClaim, ""));
            }
    
            if (!await _roleManager.RoleExistsAsync(MyApp.TesterRole)) {
                var role = new IdentityRole(MyApp.TesterRole);
                await _roleManager.CreateAsync(role);
                await _roleManager.AddClaimAsync(role, new Claim(MyApp.CanTestClaim, ""));
            }
    
            // Initialize users
            var qry = _userManager.Users;
            IdentityResult result;
    
            if (await qry.Where(x => x.UserName == AdminEmail).FirstOrDefaultAsync() == null) {
                var user = new ApplicationUser {
                    UserName = AdminEmail,
                    Email = AdminEmail,
                    FullName = "Administrator"
                };
    
                result = await _userManager.CreateAsync(user, Password);
                if (!result.Succeeded) throw new InvalidOperationException(string.Join(" | ", result.Errors.Select(x => x.Description)));
    
                result = await _userManager.AddToRoleAsync(user, MyApp.AdminRole);
                if (!result.Succeeded) throw new InvalidOperationException(string.Join(" | ", result.Errors.Select(x => x.Description)));
            }
    
            if (await qry.Where(x => x.UserName == TesterEmail).FirstOrDefaultAsync() == null) {
                var user = new ApplicationUser {
                    UserName = TesterEmail,
                    Email = TesterEmail,
                    FullName = "Tester"
                };
    
                result = await _userManager.CreateAsync(user, Password);
                if (!result.Succeeded) throw new InvalidOperationException(string.Join(" | ", result.Errors.Select(x => x.Description)));
    
                result = await _userManager.AddToRoleAsync(user, MyApp.TesterRole);
                if (!result.Succeeded) throw new InvalidOperationException(string.Join(" | ", result.Errors.Select(x => x.Description)));
            }
    
            // Roles and Claims are in a cookie. Don't expect to see them in
            // the same request that creates them (i.e., the request that
            // executes the above code to create them). You need to refresh
            // the page to create a round-trip that includes the cookie.
            var admin = User.IsInRole(MyApp.AdminRole);
            var claims = User.Claims.ToList();
    
            return View();
        }
    
        [Authorize(policy: MyApp.CanTestPolicy)]
        public IActionResult Test()
        {
            return View();
        }
    
        [Authorize(policy: MyApp.CanReportPolicy)]
        public IActionResult Report()
        {
            return View();
        }
    
        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
    }
    

    我在 "Startup" ConfigureServices 例程中注册我的身份验证策略,就在调用 services.AddMvc

    之后
        // Register authorization policies
        services.AddAuthorization(options => {
            options.AddPolicy(MyApp.CanTestPolicy,   policy => policy.RequireClaim(MyApp.CanTestClaim));
            options.AddPolicy(MyApp.CanReportPolicy, policy => policy.RequireClaim(MyApp.CanReportClaim));
        });
    

哇哦。现在,(假设我已经记下了我添加到项目中的所有适用代码,如上),当我 运行 应用程序时,我注意到我的 "built-in" 测试用户都无法访问/home/Test/home/Report 页面。此外,如果我在 Index 方法中设置断点,我会发现 User 对象中不存在我的角色和声明。但我可以查看数据库并查看所有角色和声明。

啊,从 ASP.NET 核心版本 2.0 到 2.1 有一些变化。 AddDefaultIdentity 是那个。

我不知道从你的代码从哪里开始,所以,我将提供一个示例来创建和获取用户角色。

让我们先创建UserRoles

public enum UserRoles
{
    [Display(Name = "Quản trị viên")]
    Administrator = 0,

    [Display(Name = "Kiểm soát viên")]
    Moderator = 1,

    [Display(Name = "Thành viên")]
    Member = 2
}

注意:可以去掉属性Display.

然后,我们创建 RolesExtensions class:

public static class RolesExtensions
{
    public static async Task InitializeAsync(RoleManager<IdentityRole> roleManager)
    {
        foreach (string roleName in Enum.GetNames(typeof(UserRoles)))
        {
            if (!await roleManager.RoleExistsAsync(roleName))
            {
                await roleManager.CreateAsync(new IdentityRole(roleName));
            }
        }
    }
}

接下来,在Startup.csclass,我们运行它:

    public void Configure(
        IApplicationBuilder app, 
        IHostingEnvironment env, 
        RoleManager<IdentityRole> roleManager)
    {
        // other settings...

        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });

        var task = RolesExtensions.InitializeAsync(roleManager);
        task.Wait();
    }

注意Configure需要一个返回类型void,所以我们需要创建一个任务来初始化用户角色,我们调用Wait方法。

不要像这样更改返回的类型:

public async void Configure(...)
{
    await RolesExtensions.InitializeAsync(roleManager);
}

来源:Async/Await - Best Practices in Asynchronous Programming

ConfigureServices方法中,这些配置不会工作(我们不能正确使用User.IsInRole):

services.AddDefaultIdentity<ApplicationUser>()
    //.AddRoles<IdentityRole>()
    //.AddRoleManager<RoleManager<IdentityRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

我不知道为什么 AddRolesAddRoleManager 不支持检查用户 (User.IsInRole) 的角色。

在这种情况下,我们需要像这样注册服务:

services.AddIdentity<ApplicationUser, IdentityRole>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

通过这种方式,我们在数据库中创建了3个用户角色:

注册新用户时,只需调用:

await _userManager.AddToRoleAsync(user, nameof(UserRoles.Administrator));

最后,我们可以使用[Authorize(Roles = "Administrator")]和:

if (User.IsInRole("Administrator"))
{
    // authorized
}

// or
if (User.IsInRole(nameof(UserRoles.Administrator)))
{
    // authorized
}

// but
if (User.IsInRole("ADMINISTRATOR"))
{
    // authorized
}

P/S:要实现这个目标,需要做的事情有很多。所以也许我在这个例子中遗漏了一些东西。

因此,回顾一下,问题是 ASP.NET 核心 Web 应用程序模板提供的代码为何在用户登录时不将角色或角色声明加载到 cookie 中。

经过多次谷歌搜索和试验后,似乎必须对模板代码进行两项修改才能使角色和角色声明正常工作:

首先,您必须在Startup.cs中添加以下代码行以启用RoleManager。 (OP 中提到了这一点魔法。)

services.AddDefaultIdentity<ApplicationUser>()
   .AddRoles<IdentityRole>() // <-- Add this line
    .AddEntityFrameworkStores<ApplicationDbContext>();

等等,还有更多!根据 this discussion on GitHub,让角色和声明显示在 cookie 中涉及 要么 恢复到 service.AddIdentity 初始化代码,要么坚持使用 service.AddDefaultIdentity并将这行代码添加到 ConfigureServices:

// Add Role claims to the User object
// See: https://github.com/aspnet/Identity/issues/1813#issuecomment-420066501
services.AddScoped<IUserClaimsPrincipalFactory<ApplicationUser>, UserClaimsPrincipalFactory<ApplicationUser, IdentityRole>>();

如果您阅读上面引用的讨论,您会发现角色和角色声明显然已被弃用,或者至少没有受到热切支持。就个人而言,我发现将声明分配给角色,将角色分配给用户,然后根据声明(根据角色授予用户)做出授权决策非常有用。这为我提供了一种简单的声明方式,例如,允许多个角色访问一个函数(即包含用于启用该函数的声明的所有角色)。

但您确实要注意身份验证 cookie 中携带的角色和声明数据的数量。更多数据意味着每次请求都会向服务器发送更多字节,我不知道当您遇到某种 cookie 大小限制时会发生什么。

您也可以尝试像这样修复身份验证

services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddAuthentication(options =>
{
    options.DefaultAuthenticateScheme = IdentityConstants.ApplicationScheme;
    options.DefaultChallengeScheme = IdentityConstants.ApplicationScheme;
    options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
});

如果我在 .net6 blazor wasm 中使用“角色”而不是 ClaimTypes.Role,@attribute [Authorize(Roles = "admin")] 将不起作用并得到浏览器控制台中出现此错误:

RolesAuthorizationRequirement:User.IsInRole 对于以下角色之一必须为真:(管理员)”

通过使用 ClaimTypes.Role 问题已解决:

private async Task<List<Claim>> GetClaimsAsync(User user)
{
    var claims = new List<Claim>()
    {
        new Claim("UserName", user.Email),
        new Claim("FullName", user.FirstName+" "+user.LastName),
    };
    var roles = await _userManager.GetRolesAsync(user);
    foreach (var role in roles)
        claims.Add(new Claim(ClaimTypes.Role, role)); // this line

    return claims;
}

https://github.com/mammadkoma/Attendance/blob/master/Attendance/Server/Controllers/AccountsController.cs