Example #1
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddIdentityServer()
     .AddInMemoryClients(InMemoryConfiguration.Clients())
     .AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
     .AddTestUsers(InMemoryConfiguration.Users().ToList()).AddDeveloperSigningCredential();
 }
Example #2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  b => b.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials());
            });
            var issuerUri = Configuration.GetSection("ConnectionStrings")?.GetSection("IssuerUri")?.Value;

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
                options.IssuerUri    = "https://identity-test.northeurope.cloudapp.azure.com/";
                options.PublicOrigin = Environment.IsDevelopment() ? "" : "https://identity-test.northeurope.cloudapp.azure.com/";
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddJwtBearerClientAuthentication();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            var authDbConnectionString = Configuration.GetConnectionString("MyAppOAuthContext");
            var assembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services
            .AddIdentityServer()
            //.AddDeveloperSigningCredential()
            .AddSigningCredential(new X509Certificate2(Directory.GetCurrentDirectory() + @"\Certificates\awesomenetwork.pfx", "test"))
            .AddTestUsers(InMemoryConfiguration.Users())
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(authDbConnectionString,
                                                                  sql => sql.MigrationsAssembly(assembly));
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(authDbConnectionString,
                                                                  sql => sql.MigrationsAssembly(assembly));

                // this enables automatic token cleanup. this is optional.
                //options.EnableTokenCleanup = true;
                //options.TokenCleanupInterval = 30;
            });

            services.AddMvc();
        }
Example #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            #region ²âÊÔIdentityServer4
            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          // in-memory, code config
                          .AddTestUsers(InMemoryConfiguration.Users().ToList())
                          .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources())
                          .AddInMemoryClients(InMemoryConfiguration.GetClients())
                          .AddInMemoryIdentityResources(InMemoryConfiguration.GetIdentityResources());


            builder.AddDeveloperSigningCredential();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }
            #endregion
            services.AddRazorPages();
        }
        /// <summary>
        /// 只要有关用户的身份信息单元被请求(例如在令牌创建期间或通过用户信息终点),就会调用此方法
        /// </summary>
        /// <param name="context">The context.</param>
        /// <returns></returns>
        public virtual Task GetProfileDataAsync(ProfileDataRequestContext context)
        {
            //context.LogProfileRequest(Logger);

            ////判断是否有请求Claim信息
            //if (context.RequestedClaimTypes.Any())
            //{
            //    //根据用户唯一标识查找用户信息
            //    var user = Users.FindBySubjectId(context.Subject.GetSubjectId());
            //    if (user != null)
            //    {
            //        //调用此方法以后内部会进行过滤,只将用户请求的Claim加入到 context.IssuedClaims 集合中 这样我们的请求方便能正常获取到所需Claim

            //        context.AddRequestedClaims(user.Claims);
            //    }
            //}

            //context.LogIssuedClaims(Logger);
            var user = InMemoryConfiguration.Users().FirstOrDefault(f => f.SubjectId == context.Subject.GetSubjectId());

            if (user != null)
            {
                //调用此方法以后内部会进行过滤,只将用户请求的Claim加入到 context.IssuedClaims 集合中 这样我们的请求方便能正常获取到所需Claim

                context.AddRequestedClaims(user.Claims);
            }
            return(Task.CompletedTask);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(@"D:\AspMVC\MilkSupplyManagementApi\MilkManagement.OAuth", "password123"))    // to use our own certificate
            //.AddDeveloperSigningCredential()  //AddTemporarySigningCredential
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Example #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services
            .AddIdentityServer()
            .AddSigningCredential(new X509Certificate2("identity_server_test.pfx", "password"))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc();
        }
Example #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2("/users/rmcneill/socialnetwork.pfx", "ruthy123"))
            //.AddDeveloperSigningCredential()
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc();
        }
Example #9
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddIdentityServer(options =>
     {
     })
     .AddDeveloperSigningCredential()
     .AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
     .AddInMemoryClients(InMemoryConfiguration.Clients())
     .AddTestUsers(InMemoryConfiguration.Users().ToList());
     services.AddMvc(options => options.EnableEndpointRouting = false);
 }
Example #10
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(@"C:\Users\Douglas\Documents\MisRepos\SocialNetwork\SocialNetwork.OAuth\socialnetwork.pfx", "pass123"))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryIdentityResources(InMemoryConfiguration.IdentityResources())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc();
        }
Example #11
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            //  .AddSigningCredential(new X509Certificate2(@"C:\Users\Daniil\Desktop\APP\Oauth\socialnetwork.pfx", "password"))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.GetClients())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc();
        }
Example #12
0
 // This method gets called by the runtime. Use this method to add services to the container.
 // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddIdentityServer()
     //.AddDeveloperSigningCredential()
     .AddSigningCredential(new X509Certificate2(Path.Combine(AppContext.BaseDirectory, "socialnetwork.pfx"), "12345678"))
     .AddTestUsers(InMemoryConfiguration.Users().ToList())
     .AddInMemoryClients(InMemoryConfiguration.Clients())
     .AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
     ;
     services.AddMvc();
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

            services.AddIdentityServer()
            //.AddDeveloperSigningCredential()
            .AddSigningCredential(new X509Certificate2(string.Format("{0}{1}", Directory.GetCurrentDirectory(), "\\Certificates\\IdentityServer.pfx"), "12345678"))
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddTestUsers(InMemoryConfiguration.Users().ToList());
        }
Example #14
0
        public void ConfigureServices(IServiceCollection services)
        {
            //C:\Users\ali\source\repos\CoreMicroServices\OAuthServer\socialnetwork.pfx

            //openssl req -newkey rsa:2048 -nodes -keyout socialnetwok.key -x509 -days 365 -out socialnetwork.cer
            //you may need try this command befor execute next one => winpty bash
            //openssl pkcs12 -export -in socialnetwork.cer - inkey socialnetwok.key -out socialnetwork.pfx
            services.AddIdentityServer()
            //.AddDeveloperSigningCredential()
            .AddSigningCredential(new X509Certificate2(@"socialnetwork.pfx", "password"))     //password given from pfx file which genrated by cli
            .AddTestUsers(InMemoryConfiguration.Users())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());
        }
Example #15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(
                                      @"D:\AspMVC\Identity-Server4\SocialNetwork.OAuth\SocialNetwork.OAuth\socialnetwork.pfx",
                                      "password123")) // to use our own certificate
            //.AddDeveloperSigningCredential()  //AddTemporarySigningCredential
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryIdentityResources(InMemoryConfiguration.IdentityResources())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());


            services.AddMvc();
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            //Specify How Identity Server Works
            services.AddIdentityServer()
            //Need to Specify 3 Things?
            //1. Which Api Can use this Authorization Server
            //2. Which Client Authozired to use ID4
            //3. Which Users Authorized to Use ID4
            .AddSigningCredential(new X509Certificate2(@"C:\Users\mick_\Downloads\IdentityServer4.Core2.ImplicitFlow.Token-003_Implicit_Flow_Token\IdentityServer4.Core2.ImplicitFlow.Token-003_Implicit_Flow_Token\identityserver.pfx", "Wind123456"))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryIdentityResources(InMemoryConfiguration.IdentityResources())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc();
        }
Example #17
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();

            //var assembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;
            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(@"D:\RnD\IAP\Security\IdentityProvider\src\EcoSystem\keys\ecosystem.pfx", "password"))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            //.AddConfigurationStore(builder => builder.UseSqlServer(Configuration.GetConnectionString("EcoSystem.OAuth"), options => options.MigrationsAssembly(assembly)))
            //.AddOperationalStore(builder => builder.UseSqlServer(Configuration.GetConnectionString("EcoSystem.OAuth"), options => options.MigrationsAssembly(assembly)));
            //.AddTestUsers(IdentityServer4.Quickstart.UI.TestUsers.Users)
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryIdentityResources(InMemoryConfiguration.IdentityResources())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());

            services.AddMvc();
        }
Example #18
0
        public Task ValidateAsync(ResourceOwnerPasswordValidationContext context)
        {
            //if (_users.ValidateCredentials(context.UserName, context.Password))
            //{
            //    var user = _users.FindByUsername(context.UserName);
            //    context.Result = new GrantValidationResult(
            //        user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
            //        OidcConstants.AuthenticationMethods.Password, _clock.UtcNow.UtcDateTime,
            //        user.Claims);
            //}

            var user = InMemoryConfiguration.Users().FirstOrDefault(f => f.Password == context.Password && f.Username == context.UserName);

            context.Result = new GrantValidationResult(
                user.SubjectId ?? throw new ArgumentException("Subject ID not set", nameof(user.SubjectId)),
                OidcConstants.AuthenticationMethods.Password, DateTime.UtcNow);
            return(Task.CompletedTask);
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(InMemoryConfiguration.IdentityResources())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddTestUsers(InMemoryConfiguration.Users().ToList());

            services.AddCors(options => {
                options.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyOrigin();
                    policy.AllowAnyMethod();
                    policy.AllowAnyHeader();
                });
            });

            services.AddMvc(services => services.EnableEndpointRouting = false);
        }
Example #20
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSingleton(new GetTableData(Environment.ContentRootPath));
            services.AddSingleton(new Appsettings(Environment.ContentRootPath));


            services.AddSingleton <IUserService, UserService>();
            services.AddSingleton <IRoleService, RoleService>();
            services.AddSingleton <IUserRoleService, UserRoleService>();

            #region ²âÊÔIdentityServer4
            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          // in-memory, code config
                          .AddTestUsers(InMemoryConfiguration.Users().ToList())
                          .AddInMemoryApiResources(InMemoryConfiguration.GetApiResources())
                          .AddInMemoryClients(InMemoryConfiguration.GetClients())
                          .AddInMemoryIdentityResources(InMemoryConfiguration.GetIdentityResources());
            //.AddResourceOwnerValidator<ResourceOwnerPasswordValidator>()
            //.AddProfileService<CustomProfileService>();


            builder.AddDeveloperSigningCredential();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }
            #endregion
            services.AddRazorPages();
        }
Example #21
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(@"C:\dev\todoResources.pfx", ""))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddInMemoryClients(InMemoryConfiguration.Clients())
            .AddInMemoryApiResources(InMemoryConfiguration.ApiResources());


            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = "http://localhost:5000";
                options.RequireHttpsMetadata = false;
                options.SaveToken            = true;
                options.ApiName   = "todoResources";
                options.ApiSecret = "SKB Kontur";
            });

            services.AddScoped <ToDoService>();
            services.AddMvc();
        }
Example #22
0
        public void MigrateInMemoryDataToSqlServer(IApplicationBuilder app)
        {
            using (var scope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();
                var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                context.Database.Migrate();

                if (!context.Clients.Any())
                {
                    foreach (var client in InMemoryConfiguration.Clients())
                    {
                        context.Clients.Add(client.ToEntity());
                    }

                    context.SaveChanges();
                }

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

                    context.SaveChanges();
                }

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

                    context.SaveChanges();
                }

                if (!context.ApiScopes.Any())
                {
                    foreach (var apiScope in InMemoryConfiguration.ApiScopes())
                    {
                        context.ApiScopes.Add(apiScope.ToEntity());
                    }

                    context.SaveChanges();
                }

                var applicationContext = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>();
                applicationContext.Database.Migrate();

                if (!applicationContext.Users.Any())
                {
                    foreach (var user in InMemoryConfiguration.Users())
                    {
                        var passwordHasher = new PasswordHasher <ApplicationUser>();
                        var appUser        = new ApplicationUser
                        {
                            UserName           = "******",
                            NormalizedUserName = "******",
                            CustomElement      = "custom element"
                        };

                        appUser.PasswordHash = passwordHasher.HashPassword(appUser, "Test123!");
                        applicationContext.Users.Add(appUser);
                    }

                    applicationContext.SaveChanges();
                }
            }
        }
Example #23
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var connectionString   = Configuration.GetConnectionString("DefaultConnection");
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddSingleton <IServiceConfigurationProxy, ServiceConfigurationProxy>();
            services.AddTransient <IVerificationProxy, VerificationProxy>();
            services.AddTransient <IAppletUserService, AppletUserService>();
            services.AddTransient <IPaymentServiceProxy, PaymentServiceProxy>();

            services.Configure <ApplicationSettings>(Configuration.GetSection("ApplicationSettings"));
            services.AddOptions();

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySql(connectionString));

            services.AddIdentity <ApplicationUser, IdentityRole>(options =>
            {
                // 配置身份选项
                // 密码配置
                options.Password.RequireDigit           = false; //是否需要数字(0-9).
                options.Password.RequiredLength         = 6;     //设置密码长度最小为6
                options.Password.RequireNonAlphanumeric = false; //是否包含非字母或数字字符。
                options.Password.RequireUppercase       = false; //是否需要大写字母(A-Z).
                options.Password.RequireLowercase       = false; //是否需要小写字母(a-z).

                // 锁定设置
                options.Lockout.DefaultLockoutTimeSpan  = TimeSpan.FromMinutes(30); //账户锁定时长30分钟
                options.Lockout.MaxFailedAccessAttempts = 10;                       //10次失败的尝试将账户锁定

                // 用户设置
                options.User.RequireUniqueEmail = false; //是否Email地址必须唯一
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            // Add application services.
            services.AddTransient <IEmailSender, EmailSender>();


            services.AddIdentityServer()
            .AddSigningCredential(new X509Certificate2(@"./certificate/gooios.pfx", "!QAZ2wsx098", X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.Exportable))
            .AddTestUsers(InMemoryConfiguration.Users().ToList())
            .AddConfigurationStore <ConfigurationCustomDbContext>(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            .AddOperationalStore <PersistedGrantCustomDbContext>(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseMySql(connectionString, sql => sql.MigrationsAssembly(migrationsAssembly));

                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 3600 * 24 * 7;
            })
            .AddAspNetIdentity <ApplicationUser>()
            //.AddResourceOwnerValidator<SessionKeyValidator>()
            .AddResourceOwnerValidator <CookAppSessionKeyValidator>()
            .AddProfileService <ProfileService>();



            services.AddMvc();
        }
Example #24
0
        public void MigrateInMemoryDataToSqlServer(IApplicationBuilder app)
        {
            using var scope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope();
            scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

            var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();

            context.Database.Migrate();

            if (!context.Clients.Any())
            {
                foreach (var client in InMemoryConfiguration.Clients())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
            }

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

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

            if (!context.ApiScopes.Any())
            {
                foreach (var apiScope in InMemoryConfiguration.ApiScopes())
                {
                    context.ApiScopes.Add(apiScope.ToEntity());
                }
                context.SaveChanges();
            }

            var userManager = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();

            foreach (var user in InMemoryConfiguration.Users())
            {
                var appUser = userManager.FindByNameAsync(user.Username).Result;
                if (appUser == null)
                {
                    appUser = new ApplicationUser
                    {
                        UserName       = user.Username,
                        Email          = user.Claims.Single(c => c.Type == "email").Value,
                        EmailConfirmed = true
                    };
                    var result = userManager.CreateAsync(appUser, user.Password).Result;
                    result = userManager.AddClaimsAsync(appUser, new Claim[] {
                        new Claim(JwtClaimTypes.Name, "Nils Gruson"),
                        new Claim(JwtClaimTypes.GivenName, "Nils"),
                        new Claim(JwtClaimTypes.FamilyName, "Gruson")
                    }).Result;
                }
                ;
            }
        }