简体   繁体   中英

Identity Server 4 Asp.Net Identity + EF Core not Seeding

I have basically followed the whole tutorial from scratch, besides skipping javascript client. However, i copied some code from the sample Asp.Net Identity + EF Core combined and database with all tables was created successfully. However, when i run the identity server, there is no seed. I debugged the program.cs and the seed var is always false making it skipping the seed condition.

public class Program
{
    public static void Main(string[] args)
    {
        var seed = args.Any(x => x == "/seed");
        if (seed) args = args.Except(new[] { "/seed" }).ToArray();

        var host = CreateWebHostBuilder(args).Build();

        if (seed)
        {
            using (var scope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
            {
                SeedData.EnsureSeedData(scope.ServiceProvider);
                return;
            }
        }

        host.Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

this is the seed data class just like in the sample

 public class SeedData
{
    public static void EnsureSeedData(IServiceProvider provider)
    {
        provider.GetRequiredService<ApplicationDbContext>().Database.Migrate();
        provider.GetRequiredService<PersistedGrantDbContext>().Database.Migrate();
        provider.GetRequiredService<ConfigurationDbContext>().Database.Migrate();

        {
            var userMgr = provider.GetRequiredService<UserManager<ApplicationUser>>();
            var alice = userMgr.FindByNameAsync("alice").Result;
            if (alice== null)
            {
                alice = new ApplicationUser
                {
                    UserName = "alice"
                };
                var result = userMgr.CreateAsync(alice, "Pass123$").Result
                if (!result.Succeeded)
                {
                    throw new Exception(result.Errors.First().Description);
                }

                alice = userMgr.FindByNameAsync("alice").Result;

                result = userMgr.AddClaimsAsync(user, new Claim[]{
                            new Claim(JwtClaimTypes.Subject, "1"),
                            new Claim(JwtClaimTypes.Name, "Alice Smith"),
                            new Claim(JwtClaimTypes.GivenName, "Alice"),
                            new Claim(JwtClaimTypes.FamilyName, "Smith"),
                              new Claim(JwtClaimTypes.Email, "AliceSmith@email.com"),
                            new Claim(JwtClaimTypes.EmailVerified, "true", ClaimValueTypes.Boolean),
                            new Claim(JwtClaimTypes.Role, "Admin")                                
                        }).Result;
                if (!result.Succeeded)
                {
                    throw new Exception(result.Errors.First().Description);
                }
                Console.WriteLine("user created");
            }
            else
            {
                Console.WriteLine("user already exists");
            }                
        }

        {
            var context = provider.GetRequiredService<ConfigurationDbContext>();
            if (!context.Clients.Any())
            {
                foreach (var client in Config.GetClients())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }

            if (!context.IdentityResources.Any())
            {
                foreach (var resource in Config.GetIdentityResources())
                {
                    context.IdentityResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }

            if (!context.ApiResources.Any())
            {
                foreach (var resource in Config.GetApis())
                {
                    context.ApiResources.Add(resource.ToEntity());
                }
                context.SaveChanges();
            }
        }
    }
}

what am i missing? Everything code wise is the same, startup class too etc...

For passing string[] args , you need to launch project by Project.exe instead of IIS Express .

Follow Project Properties->Debug->Application Arguments-> /seed ->Launch Project from ProjectName .

In general, you may consider deciding seeding data by check wether there is any data in database instead of from command arguments.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM