Search code examples
c#asp.net.net-coreasp.net-identity.net-7.0

.NET Core 7: Store does not implement IUserRoleStore<TUser>


I encountered the following error while trying to add a role to a user:

Store does not implement IUserRoleStore.

How can I resolve this error?

I am using .NET 7.

public static async Task SeedUsersAsync(UserManager<ApplicationUser> userManager)
{
                if (!userManager.Users.Any())
                {
                    var user = new ApplicationUser
                    {
                        DisplayName = "Bob",
                        Email = "bob@test.com",
                        UserName = "bob@test.com",
                        Address = new Address
                        {
                            FirstName = "Bob",
                            LastName = "Bobbity",
                            Street = "10 The street",
                            City = "New York",
                            State = "NY",
                            ZipCode = "90210"
                        },
                        EmailConfirmed = true,
                    };
                    await userManager.CreateAsync(user, "Pa$$w0rd");
                    await userManager.AddToRoleAsync(user, Roles.Standard.ToString("f")); // Error happend here!
              }
}

IdentityServiceExtensions:

 public static class IdentityServiceExtensions
    {
        public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
        {
            var builder = services.AddIdentityCore<ApplicationUser>();

            builder = new IdentityBuilder(builder.UserType, builder.Services);
            builder.AddEntityFrameworkStores<ShopDbContext>();
            builder.AddSignInManager<SignInManager<ApplicationUser>>();

            builder.Services.AddIdentity<ApplicationUser, ApplicationRole>()
                .AddEntityFrameworkStores<ShopDbContext>();
               

            services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
            .AddJwtBearer(options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(config["Token:Key"])),
                    ValidIssuer = config["Token:Issuer"],
                    ValidateIssuer = true,
                    ValidateAudience = false
                };
            });

            
            services.AddAuthorization(opts =>
            {
                opts.AddPolicy(PolicyType.RequireSuperAdminRole.ToString("f"), policy => policy.RequireRole("SuperAdmin"));
                opts.AddPolicy(PolicyType.RequireAdministratorRole.ToString("f"), policy => policy.RequireRole("Admin", "SuperAdmin"));
                opts.AddPolicy(PolicyType.RequireStandardRole.ToString("f"), policy => policy.RequireRole("Basic", "Admin", "SuperAdmin"));
            });

            return services;
        }
    }

Program.cs:

using var scope = app.Services.CreateScope();
var services = scope.ServiceProvider;
var loggerFactory = services.GetRequiredService<ILoggerFactory>();
try
{
    var context = services.GetRequiredService<ShopDbContext>();

    var userManager = services.GetRequiredService<UserManager<ApplicationUser>>();
    var roleManager = services.GetRequiredService<RoleManager<ApplicationRole>>();

    await context.Database.MigrateAsync();
    await ShopContextSeed.SeedAsync(context, loggerFactory);
    await IdentityContextSeed.SeedRolesAsync(roleManager);
    await IdentityContextSeed.SeedUsersAsync(userManager);
}
catch (Exception ex)
{
    var logger = loggerFactory.CreateLogger<Program>();
    logger.LogError(ex, "An error occurred during migration");
}

Solution

  • I resolved the issue by adding builder.AddRoles<ApplicationRole>() and removing the line builder.Services.AddIdentity<ApplicationUser, ApplicationRole>().

    public static IServiceCollection AddIdentityServices(this IServiceCollection services, IConfiguration config)
    {
        var builder = services.AddIdentityCore<ApplicationUser>();
    
        builder = new IdentityBuilder(builder.UserType, builder.Services);
                builder.AddSignInManager<SignInManager<ApplicationUser>>();
                builder.AddRoles<ApplicationRole>();
                builder.AddEntityFrameworkStores<ShopDbContext>();
                
                
       // rest of the code ...
    }