1

I got this, when I wanted to add a role to a user.

Store does not implement IUserRoleStore.

How can I solve this error?

I used .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");
}
x19
  • 8,277
  • 15
  • 68
  • 126
  • Try `builder.Services.AddIdentity().AddRoles().AddEntityFrameworkStores();` - you haven't done `AddRoles` to be able to `AddToRoleAsync` - does that work? – Ermiya Eskandary Nov 15 '22 at 00:52
  • I did it, but I got the same error. – x19 Nov 15 '22 at 00:56
  • I didn't use AddToRoleAsync – x19 Nov 15 '22 at 00:58
  • You've used `await userManager.AddToRoleAsync` - can you please update the question with the new code? – Ermiya Eskandary Nov 15 '22 at 01:03
  • Thats'r right. I have written await userManager.AddToRoleAsync(user, Roles.Standard.ToString("f")); in SeedUsersAsync method – x19 Nov 15 '22 at 01:09
  • 1
    Ah I can notice you've done `builder.AddEntityFrameworkStores();` twice - remove the first one and then modify the second instance as I've mentioned above (`AddRoles` before `AddEntityFrameworkStores`). Does that make a difference? Please update your code regardless so it's clear what the latest version is. – Ermiya Eskandary Nov 15 '22 at 01:18
  • @ErmiyaEskandary: The problem still persists! I asked another question related to this problem. Please visit this link: https://stackoverflow.com/q/74450132/1817640 – x19 Nov 16 '22 at 11:53

1 Answers1

0

I added builder.AddRoles<ApplicationRole>() and removed builder.Services.AddIdentity.

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 ...
}
x19
  • 8,277
  • 15
  • 68
  • 126