首页 文章

如何在ASP.NET Core 2.1中使用角色?

提问于
浏览
10

我使用以下方法创建了一个测试项目:

dotnet new razor --auth Individual --output Test

这将创建一个Startup.cs,其中包含:

public void ConfigureServices(IServiceCollection services)
{
    services.Configure<CookiePolicyOptions>(options =>
    {
        // This lambda determines whether user consent for non-essential cookies is needed for a given request.
        options.CheckConsentNeeded = context => true;
        options.MinimumSameSitePolicy = SameSiteMode.None;
    });

    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlite(
            Configuration.GetConnectionString("DefaultConnection")));

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

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

我想为一些用户和角色提供种子 . 用户和角色都将使用同一个商店(SQLite) . 我'm using a static class for seeding which it'从 Program 打来电话 .

我可以播种用户,但不能播放角色,因为上面似乎没有注入 RoleManager .

在ASP.NET Core 2.0中使用以下内容:

services.AddIdentity<IdentityUser, IdentityRole>()

我猜 AddDefaultIdentity 在2.1中是新的,但问题是它没有注入 RoleMnager ,所以我该怎么办?

3 回答

  • 15

    似乎最终Microsoft理解并非每个应用程序都需要角色并将它们分开 .

    请注意 AddDefaultIdentity 声明为:

    public static IdentityBuilder AddDefaultIdentity<TUser>(this IServiceCollection services) where TUser : class;
    

    因此,您可以继续通过 IdentityBuilder 配置身份选项 . 你想要做的是:

    services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>();
    

    幸运的是,他们还删除了 IUserIRole 约束,因此现在您可以在完全独立的程序集中使用模型,而无需安装数百个NuGet包 .

  • 3

    可能会帮助其他人:如果您通过脚手架将asp.net身份添加到现有项目中,则需要编辑 IdentityHostingStartup.cs 并在那里更改服务而不是在您的启动类中:

    services.AddIdentity<AppUser, IdentityRole>()
                    .AddDefaultUI()
                    .AddRoles<IdentityRole>()
                    .AddRoleManager<RoleManager<IdentityRole>>()
                    .AddDefaultTokenProviders()
                    .AddEntityFrameworkStores<authContext>();
    

    然后,您可以在种子中使用角色管理器 .

  • 9

    除了已经提供的答案之外,尽管添加了 .AddRoles<Identity>() ,但在我的控制器上使用 Authorize(Roles = "Administrator") 时仍然无法获得授权 . 出于某种原因,"role claim doesn't seem to affect IsUserInRole or AuthorizeAttribute with a role name."

    为了利用角色,我建议使用ASP.NET 2.0方式,如下所示:

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

    这样,您就可以使用自己的角色,并获得为您搭建的身份页面 .

    请参阅aspnet github上的这个问题:Issue 1813

相关问题