コード例 #1
0
ファイル: Startup.cs プロジェクト: ZumoCommunity/Identity-API
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var logger = _loggerFactory.CreateLogger("ConfigureServices");


            //Add configuration service
            services.AddSingleton <IConfiguration>(Configuration);

            logger.LogInformation("Initializing ASP.NET Identity");
            // Add ASP.NET Identity services.
            services.AddIdentity <User, string>(opts => {
                //opts.Cookies.ApplicationCookie.LoginPath = new PathString("/Account/SignIn");
                //opts.Cookies.ApplicationCookie.LogoutPath = new PathString("/Account/SignOut");
                //opts.Cookies.ApplicationCookie.AccessDeniedPath = new PathString("/Account/AccessDenied");
                //opts.Cookies.ApplicationCookie.ExpireTimeSpan = TimeSpan.FromHours(2);
                //opts.Cookies.ApplicationCookie.SlidingExpiration = true;

                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireUppercase       = false;
                opts.Password.RequireDigit           = false;
            })
            .AddIdentityUserServices()
            .AddDefaultTokenProviders();



            logger.LogInformation("Initializing IdentityServer4 services");
            //Add IdentityServer4 services
            services.AddSingleton <IClientStore, ZumoClientStore>();


            string certFilePath = "IdentityApi.pfx";
            string certPassword = Configuration.GetValue <string>("CERT_PWD");

            var identityServerBuilder = services.AddIdentityServer(opts => {
                opts.UserInteraction.LoginUrl = "/Account/Login";
            })
                                        .AddDefaultEndpoints()
                                        .AddInMemoryIdentityResources(IdentityServerData.GetIdentityResources())
                                        .AddInMemoryApiResources(IdentityServerData.GetApiResources())
                                        .AddAspNetIdentity <User>();

            try {
                logger.LogInformation("Loading certificate PFX");
                //loading certificate as pfx file
                var certificate = new X509Certificate2(certFilePath, certPassword, X509KeyStorageFlags.MachineKeySet);
                identityServerBuilder.AddSigningCredential(certificate);

                //loading certificate from machine storage (!!!!!!! doesn't work by some reason - need to figure out why)
                //identityServerBuilder.AddSigningCredential("ZumoCommunity.IdentityApi");
            }
            catch (Exception ex) {
                //If not available - generate temporary
                identityServerBuilder.AddTemporarySigningCredential();
                logger.LogError(99, ex, ex.Message);
                InitErrors += ex.Message + "\n" + ex.StackTrace;
            }


            //services.AddIdentityServer()
            //    .AddTemporarySigningCredential()
            //    .AddInMemoryPersistedGrants()
            //    .AddInMemoryIdentityResources(Config.GetIdentityResources())
            //    .AddInMemoryApiResources(Config.GetApiResources())
            //    .AddInMemoryClients(Config.GetClients())
            //    .AddAspNetIdentity<ApplicationUser>();


            logger.LogInformation("Initializing MVC services");
            services.AddMvc();


            logger.LogInformation("Initializing Swagger services");
            //Add swagger services
            var pathToDoc = "IdentityApi.Host.xml";  //Configuration["Swagger:XmlDocPath"];

            services.AddSwaggerGen();
            services.ConfigureSwaggerGen(options => {
                options.SingleApiVersion(new Swashbuckle.Swagger.Model.Info {
                    Version        = "v1",
                    Title          = "Identity API",
                    Description    = "Identity microservice",
                    TermsOfService = "None"
                });
                options.IncludeXmlComments(pathToDoc);
            });

            logger.LogInformation("Add other application services");

            services.AddScoped <IUserService, UserService>();

            // Add application services.
            services.AddSingleton <ILookupNormalizer>(new LowerInvariantLookupNormalizer());

            services.AddTransient <IEmailSender, AuthMessageSender>();
            services.AddTransient <ISmsSender, AuthMessageSender>();

            services.AddTransient <ITestDataInitializer, TestDataInitializer>();
        }
コード例 #2
0
        /// <summary>
        /// Generate default clients, identity and api resources
        /// </summary>
        private static async Task EnsureSeedIdentityServerData <TIdentityServerDbContext>(TIdentityServerDbContext context, IdentityServerData identityServerDataConfiguration)
            where TIdentityServerDbContext : DbContext, IAdminConfigurationDbContext
        {
            foreach (var resource in identityServerDataConfiguration.IdentityResources)
            {
                var exits = await context.IdentityResources.AnyAsync(a => a.Name == resource.Name);

                if (exits)
                {
                    continue;
                }

                await context.IdentityResources.AddAsync(resource.ToEntity());
            }

            foreach (var apiScope in identityServerDataConfiguration.ApiScopes)
            {
                var exits = await context.ApiScopes.AnyAsync(a => a.Name == apiScope.Name);

                if (exits)
                {
                    continue;
                }

                await context.ApiScopes.AddAsync(apiScope.ToEntity());
            }

            foreach (var resource in identityServerDataConfiguration.ApiResources)
            {
                var exits = await context.ApiResources.AnyAsync(a => a.Name == resource.Name);

                if (exits)
                {
                    continue;
                }

                foreach (var s in resource.ApiSecrets)
                {
                    s.Value = s.Value.ToSha256();
                }

                await context.ApiResources.AddAsync(resource.ToEntity());
            }


            foreach (var client in identityServerDataConfiguration.Clients)
            {
                var exits = await context.Clients.AnyAsync(a => a.ClientId == client.ClientId);

                if (exits)
                {
                    continue;
                }

                foreach (var secret in client.ClientSecrets)
                {
                    secret.Value = secret.Value.ToSha256();
                }

                client.Claims = client.ClientClaims
                                .Select(c => new ClientClaim(c.Type, c.Value))
                                .ToList();

                await context.Clients.AddAsync(client.ToEntity());
            }

            await context.SaveChangesAsync();
        }