使用 ASP:Net Identity 2.1 检查角色不起作用

Checking roles with ASP:Net Identity 2.1 does not work

我将 ASP.Net MVC 核心应用程序从 1.1 升级到 2.1,包括将 ASP.Net Identity 从 1.1 迁移到 2.1。

我得到了一些东西,包括 ASP.Net Identity EntityFramework 使用 Sqlite 的集成。

我的 startup.cs 配置看起来像 this:

        services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<ApplicationDbContext>();

        services.Configure<IdentityOptions>(options =>
        {
            // Password settings.
            options.Password.RequireDigit = true;
            options.Password.RequireLowercase = true;
            options.Password.RequireNonAlphanumeric = true;
            options.Password.RequireUppercase = true;
            options.Password.RequiredLength = 6;
            options.Password.RequiredUniqueChars = 1;

            // Lockout settings.
            options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);
            options.Lockout.MaxFailedAccessAttempts = 5;
            options.Lockout.AllowedForNewUsers = true;

            // User settings.
            options.User.AllowedUserNameCharacters =
            "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+";
            options.User.RequireUniqueEmail = false;
        });

        services.AddAuthentication()
            .AddMicrosoftAccount(options =>
            {
                options.ClientId = Configuration["Authentication:Microsoft:ClientId"];
                options.ClientSecret = Configuration["Authentication:Microsoft:ClientSecret"];
            });

        services.AddAuthorization(options =>
        {
            options.AddPolicy(PolicyNames.RequireTauchbold, policy => policy.RequireRole(Rolenames.Tauchbold));
        });

在 Configure() 中我有:

app.UseAuthentication();

然后在我的控制器中我有:

[Authorize(Policy = PolicyNames.RequireTauchbold)]
public class EventController : Controller
{
    ...

完整的源代码可以在 GitHub 上找到。

问题

问题是,即使我正确登录并分配了角色,上述对控制器的检查总是 return "access denied"。我不知道这会出错。有人知道我会错过什么吗 here

更新

我认为,普通的空 [Authorize] 属性有效(强制登录)但 [Authorize(Policy = '...')] 无法识别该角色。我已经检查了数据库表,但它们对我来说看起来不错。除了 ÀspNetUsersAspNetRolesAspNetUserRoles 之外,我还需要在数据库中配置其他任何东西吗?

更新 2:

我使用@itminus 的解决方案使其工作,但必须在启动时添加对 AddDefaultUI() 的调用才能使登录和注册再次工作。所以我的启动现在包含这些行来配置身份:

        services.AddIdentity<IdentityUser, IdentityRole>()
            .AddRoleManager<RoleManager<IdentityRole>>()
            .AddDefaultUI()
            .AddEntityFrameworkStores<ApplicationDbContext>();

我刚刚测试了您的代码。由于2.1.x版本中的AddDefaultIdentity<IdentityUser>()默认不会启用Role,我将您的代码更改如下:

//services.AddDefaultIdentity<IdentityUser>()
//    .AddEntityFrameworkStores<ApplicationDbContext>();

services.AddIdentity<IdentityUser, IdentityRole>()
    .AddRoleManager<RoleManager<IdentityRole>>()
    .AddEntityFrameworkStores<ApplicationDbContext>();

为了使用上面的代码进行测试,我注册了一个新用户并为该用户添加了角色:

await _roleManager.CreateAsync(new IdentityRole(Rolenames.Tauchbold));
var user= await _userManager.GetUserAsync(HttpContext.User);
await _userManager.AddToRoleAsync(user, Rolenames.Tauchbold);

先退出再登录,现在可以了: