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

Ala*_*n T 14 c# asp.net-core asp.net-core-identity asp.net-core-2.1

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

dotnet new razor --auth Individual --output Test
Run Code Online (Sandbox Code Playgroud)

这将创建一个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);
}
Run Code Online (Sandbox Code Playgroud)

我想为一些用户和角色提供种子.用户和角色都将使用同一个商店(SQLite).我正在使用一个静态类来播种它Program.

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

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

services.AddIdentity<IdentityUser, IdentityRole>()
Run Code Online (Sandbox Code Playgroud)

我猜测AddDefaultIdentity2.1是新的,但问题是它没有注入RoleMnager,所以我该怎么办?

SO *_*ood 20

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

请注意,AddDefaultIdentity声明为:

public static IdentityBuilder AddDefaultIdentity<TUser>(this IServiceCollection services) where TUser : class;
Run Code Online (Sandbox Code Playgroud)

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

services.AddDefaultIdentity<IdentityUser>().AddRoles<IdentityRole>();
Run Code Online (Sandbox Code Playgroud)

幸运的是,他们也去掉了IUserIRole约束,所以现在你可以在一个完全独立的组件使用的模型,而无需安装数以百计的NuGet包.

  • 真棒!我可以确认这是我想做的.感谢您及时的回复. (2认同)

Jon*_*ine 13

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

services.AddIdentity<AppUser, IdentityRole>()
                .AddDefaultUI()
                .AddRoles<IdentityRole>()
                .AddRoleManager<RoleManager<IdentityRole>>()
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<authContext>();
Run Code Online (Sandbox Code Playgroud)

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


elf*_*ico 5

除了已经提供的答案之外,尽管添加了 ,但在我的控制器上.AddRoles<Identity>()使用时仍然无法获得授权Authorize(Roles = "Administrator")。出于某种原因,“角色声明似乎不会影响具有角色名称的 IsUserInRole 或 AuthorizeAttribute”。

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

services.AddIdentity<IdentityUser, IdentityRole>()
            .AddDefaultUI()
            .AddDefaultTokenProviders()
            .AddEntityFrameworkStores<ApplicationDbContext>();
Run Code Online (Sandbox Code Playgroud)

这样,您就可以使用您的角色,并为您搭建身份页面。

在aspnet github上参考这个问题: Issue 1813

  • 我也偶然发现了这个,但没有更新我上面的回复。我的 IdentityHostingStartup.cs 文件现在包含: services.AddIdentity&lt;AppUser, IdentityRole&gt;() .AddDefaultUI() .AddRoles&lt;IdentityRole&gt;() .AddRoleManager&lt;RoleManager&lt;IdentityRole&gt;&gt;() .AddDefaultTokenProviders() .AddEntityFrameworkStores&lt;authContext&gt;() ; (2认同)