Search code examples
c#asp.net-coreasp.net-core-identityasp.net-core-2.1

How to use Roles in ASP.NET Core 2.1?


I've created a test project using:

dotnet new razor --auth Individual --output Test

This creates a Startup.cs that contains:

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);
}

I want to seed some users and roles. Both users and roles will use the same store (SQLite). I'm using a static class for seeding which it's called from Program.

I can seed users, but not roles, since the above does not seem to inject a RoleManager.

In ASP.NET Core 2.0 the following is used:

services.AddIdentity<IdentityUser, IdentityRole>()

I'm guessing AddDefaultIdentity is new in 2.1 but the problem is that it does not inject a RoleMnager, so what should I do?


Solution

  • It seems that finally Microsoft understood that not every application needs roles and separated them.

    Notice that AddDefaultIdentity is declared as:

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

    So, you can continue to configure Identity options through that IdentityBuilder. What you want to do is:

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

    Fortunately, they also removed the IUser and IRole constrains, so now you can use models in a completely separate assembly without having to install hundreds of NuGet packages.