Ejemplo n.º 1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            IFreeSql freeSql = new FreeSql.FreeSqlBuilder()
                               .UseConnectionString(FreeSql.DataType.SqlServer, Configuration.GetConnectionString("meta"))
                               .Build();

            services.AddSingleton(freeSql);
            services.AddSingleton <IAdminService, AdminService>();

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

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityConfig.GetClients());

            //services.AddCors(options =>
            //{
            //    // this defines a CORS policy called "default"
            //    options.AddPolicy("default", policy =>
            //    {
            //        policy.WithOrigins("*")
            //            .AllowAnyHeader()
            //            .AllowAnyMethod();
            //    });
            //});
        }
Ejemplo n.º 2
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            //CORS
            services.ConfigureCors();

            //EF
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseMySql(Configuration.GetConnectionString(DbConnection)));

            //Adding  ASP Identity
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            //Identity Server
            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryClients(IdentityConfig.GetClients())
            .AddAspNetIdentity <ApplicationUser>();

            //identity server profile service
            services.AddTransient <IProfileService, IdentityClaimsProfileService>();


            //authentication JWT
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(options =>
            {
                // base-address of your identityserver
                options.Authority = Configuration.GetValue <string>(AuthUrl);
                // name of the API resource
                options.Audience             = Configuration.GetValue <string>(Key);
                options.RequireHttpsMetadata = false;
            });

            //auto mapper
            var mappingConfig = new MapperConfiguration(mc =>
            {
                mc.AddProfile(new AutoMapperProfile());
            });
            IMapper mapper = mappingConfig.CreateMapper();

            services.AddSingleton(mapper);

            //MVC
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.ContractResolver
                    = new Newtonsoft.Json.Serialization.DefaultContractResolver();
            });;
        }
Ejemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <IdentityServerDbContext>
                (options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <ApplicationUser, IdentityRole>(opt =>
            {
                opt.Password.RequireDigit           = false;
                opt.Password.RequiredLength         = 4;
                opt.Password.RequireNonAlphanumeric = false;
                opt.Password.RequireUppercase       = false;
                opt.Password.RequireLowercase       = false;
            })
            .AddEntityFrameworkStores <IdentityServerDbContext>()
            .AddDefaultTokenProviders();


            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryClients(IdentityConfig.GetClients(Configuration))
            .AddAspNetIdentity <ApplicationUser>();


            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Ejemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            // configure identity server with in-memory stores, keys, clients and scopes
            services.AddIdentityServer()
            .AddTemporarySigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryClients(IdentityConfig.GetClients())
            .AddTestUsers(IdentityConfig.GetUsers());

            services.AddAuthorization(auth =>
            {
                auth.AddSecurity();
            });

            services.AddSingleton <IUserDataService, UserDataService>();

            services.AddSingleton <IUserRepository, UserRepository>();
            services.AddSingleton <IUserRoleRepository, UserRoleRepository>();

            Action <AccountService.AccountServiceOptions> options = (opt =>
            {
                opt.AppDBConnection = Configuration["ConnectionStrings:DefaultConnection"];
            });

            services.Configure(options);
            services.AddSingleton(resolver => resolver.GetRequiredService <IOptions <AccountService.AccountServiceOptions> >().Value);

            services.AddMvc();
        }
Ejemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            var sqlConnection = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext <ApplicationDbContext>(options => options.UseSqlServer(sqlConnection));

            services.AddIdentity <ApplicationUser, IdentityRole>(opts => {
                opts.Password.RequireDigit           = false;
                opts.Password.RequiredLength         = 4;
                opts.Password.RequireNonAlphanumeric = false;
                opts.Password.RequireUppercase       = false;
                opts.Password.RequireLowercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryClients(IdentityConfig.GetClients(
                                    Configuration
                                    ))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <ProfileService>();

            services.AddMvc();
        }
Ejemplo n.º 6
0
        private void InitializeDatabase(IApplicationBuilder app, IdentityConfig identityConfig, bool recreateDatabases = false)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                var persistantGrantDb = serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database;
                if (recreateDatabases)
                {
                    persistantGrantDb.EnsureDeleted();
                    persistantGrantDb.Migrate();
                }

                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                if (recreateDatabases)
                {
                    context.Database.EnsureDeleted();
                    context.Database.Migrate();
                }
                if (!context.ApiResources.Any())
                {
                    context.ApiResources.AddRange(identityConfig.GetApiResources().Select(x => x.ToEntity()));
                    context.SaveChanges();
                }
                if (!context.Clients.Any())
                {
                    context.Clients.AddRange(identityConfig.GetClients().Select(x => x.ToEntity()));
                    context.SaveChanges();
                }

                if (!context.IdentityResources.Any())
                {
                    context.IdentityResources.AddRange(identityConfig.GetIdentityResources().Select(x => x.ToEntity()));
                    context.SaveChanges();
                }
            }
        }
Ejemplo n.º 7
0
        private void AddAuth(IServiceCollection services)
        {
            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Identity/Account/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
            })
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryApiScopes(IdentityConfig.GetApiScopes())
            .AddInMemoryClients(IdentityConfig.GetClients(Configuration))
            .AddInMemoryPersistedGrants()
            .AddAspNetIdentity <User>()
            .AddDeveloperSigningCredential();

            services
            .AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            .AddJwtBearer(IdentityServerAuthenticationDefaults.AuthenticationScheme, options =>
            {
                options.Authority            = Configuration.GetSection("IdentityServer").GetValue <string>("AuthorityUrl");
                options.RequireHttpsMetadata = true;
                options.Audience             = "pzph.api";
                options.SaveToken            = true;
            });

            services.AddAuthorization(settings =>
            {
                settings.AddPolicy(
                    "user",
                    policy => policy.RequireAuthenticatedUser().RequireClaim("scope", "pzph.api"));
            });
        }
Ejemplo n.º 8
0
        private static void EnsureSeedData(ConfigurationDbContext context, UserManager <ApplicationUser> userManager)
        {
            if (!context.Clients.Any())
            {
                foreach (var client in IdentityConfig.GetClients().ToList())
                {
                    context.Clients.Add(client.ToEntity());
                }
                context.SaveChanges();
                //
                foreach (var user in IdentityConfig.GetUsers())
                {
                    userManager.CreateAsync(new ApplicationUser {
                        UserName = user.Username
                    }, user.Password);
                }
            }

            if (!context.Scopes.Any())
            {
                foreach (var client in IdentityConfig.GetScopes().ToList())
                {
                    context.Scopes.Add(client.ToEntity());
                }
                context.SaveChanges();
            }
        }
Ejemplo n.º 9
0
        public void InitializeDatabase(IApplicationBuilder app)
        {
            using (var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope())
            {
                serviceScope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                var context = serviceScope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                context.Database.Migrate();
                if (!context.Clients.Any())
                {
                    foreach (var client in IdentityConfig.GetClients())
                    {
                        context.Clients.Add(client.ToEntity());
                    }

                    context.SaveChanges();
                }

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

                    context.SaveChanges();
                }

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

                    context.SaveChanges();
                }

                if (!context.ApiScopes.Any())
                {
                    foreach (var resource in IdentityConfig.GetScopes())
                    {
                        context.ApiScopes.Add(resource.ToEntity());
                    }

                    context.SaveChanges();
                }
            }
        }
Ejemplo n.º 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)
        {
            var cert = new X509Certificate2
                           (Path.Combine(webHostEnvironmentv.ContentRootPath,
                                         configuration["IdentityServer:FileName"]),
                           configuration["IdentityServer:Password"],
                           X509KeyStorageFlags.MachineKeySet);

            services.AddIdentityServer()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiScopes(IdentityConfig.ApiScopes)
            .AddInMemoryApiResources(IdentityConfig.ApiResources)
            .AddInMemoryClients(IdentityConfig.GetClients())
            .AddTestUsers(IdentityConfig.GestUsers())
            .AddSigningCredential(cert)
            //.AddDeveloperSigningCredential()
            ;
        }
Ejemplo n.º 11
0
 // This method gets called by the runtime. Use this method to add services to the container.
 public void ConfigureServices(IServiceCollection services)
 {
     services.AddDbContext <ApplicationDbContext>(options => options.UseMySql(
                                                      Configuration.GetConnectionString("DefaultConnection")));
     //身份验证配置
     services.AddIdentity <ApplicationUser, ApplicationRole>()
     .AddEntityFrameworkStores <ApplicationDbContext>()
     .AddDefaultTokenProviders()
     .AddClaimsPrincipalFactory <ClaimsPrincipalFactory>();
     //认证服务器配置
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
     .AddInMemoryApiResources(IdentityConfig.GetApiResources())
     .AddInMemoryClients(IdentityConfig.GetClients())
     .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
     .AddProfileService <ProfileService>();
     services.AddHealthChecks();
 }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <simepadfContext>(
                //options => options.UseSqlServer(Configuration.GetConnectionString("DataBase"))
                options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
                );

            services.AddMyDependecies(Configuration);

            services.AddIdentity <Usuario, IdentityRole>(config =>
            {
                config.SignIn.RequireConfirmedEmail = true;
            })
            .AddEntityFrameworkStores <simepadfContext>()
            .AddDefaultTokenProviders();

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryClients(IdentityConfig.GetClients(
                                    Configuration
                                    ))
            .AddAspNetIdentity <Usuario>()        //usuario
            .AddProfileService <ProfileService>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <AuthMessageSenderOptions>(Configuration);

            // Email Service
            services.AddSingleton <IEmailConfiguration>(Configuration.GetSection("EmailConfiguration").Get <EmailConfiguration>());
            services.AddTransient <IEmailService, EmailService>();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <CodenationContext>();
            services.AddScoped <IResourceOwnerPasswordValidator, PasswordValidatorService>();
            services.AddScoped <IProfileService, UserProfileService>();
            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
                          .AddInMemoryApiResources(IdentityConfig.GetApis())
                          .AddInMemoryClients(IdentityConfig.GetClients())
                          .AddProfileService <UserProfileService>();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("ambiente de produção precisa de chave real");
            }
        }
 /// <summary>
 /// 认证服务
 /// </summary>
 /// <param name="services"></param>
 /// <param name="configuration"></param>
 /// <returns></returns>
 public static void AddAuthService(this IServiceCollection services, IConfiguration configuration)
 {
     //认证服务器配置
     services.AddIdentityServer()
     .AddDeveloperSigningCredential()
     .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
     .AddInMemoryApiResources(IdentityConfig.GetApiResources())
     .AddInMemoryApiScopes(IdentityConfig.GetApiScope())
     .AddInMemoryClients(IdentityConfig.GetClients())
     .AddResourceOwnerValidator <PasswordValidator>()
     .AddProfileService <ProfileService>();
     //资源服务器配置
     services.AddAuthentication(options =>
     {
         options.DefaultAuthenticateScheme = IdentityServerAuthenticationDefaults.AuthenticationScheme;
         options.DefaultScheme             = JwtBearerDefaults.AuthenticationScheme;
         options.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
         options.DefaultForbidScheme       = JwtBearerDefaults.AuthenticationScheme;
     }).AddIdentityServerAuthentication(options =>
     {
         options.Authority            = configuration["ApplicationConfiguration:Url"];
         options.RequireHttpsMetadata = false;
         options.ApiName = "api";
         options.Events  = new JwtBearerEvents
         {
             OnMessageReceived = context =>
             {
                 if (context.Request.Query.TryGetValue("token", out StringValues token))
                 {
                     context.Token = token;
                 }
                 return(Task.CompletedTask);
             },
             OnAuthenticationFailed = context =>
             {
                 var te = context.Exception;
                 return(Task.CompletedTask);
             }
         };
     });
 }
Ejemplo n.º 15
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <AppDB>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            //Se setean las consideraciones para las contrasenas.
            services.AddIdentity <CUser, IdentityRole>
            (
                identityoptions =>
            {
                identityoptions.Password.RequireDigit           = true;
                identityoptions.Password.RequiredLength         = 6;
                identityoptions.Password.RequireNonAlphanumeric = false;
                identityoptions.Password.RequireUppercase       = true;
                identityoptions.Password.RequireLowercase       = false;
                identityoptions.User.AllowedUserNameCharacters  = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.";
                identityoptions.User.RequireUniqueEmail         = true;
            }
            ).AddEntityFrameworkStores <AppDB>().AddDefaultTokenProviders();

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetAPIResources())
            .AddInMemoryClients(IdentityConfig.GetClients(
                                    Configuration
                                    ))
            .AddAspNetIdentity <CUser>()
            .AddProfileService <ProfileService>();

            //services.Configure<CookiePolicyOptions>(options =>
            //{
            //    // This lambda determines whether user consent for non-essential cookies is needed for a given request.
            //    options.CheckConsentNeeded = context => true;
            //    options.MinimumSameSitePolicy = SameSiteMode.None;
            //});


            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
        }
Ejemplo n.º 16
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers()
            .AddNewtonsoftJson();

            services.AddHttpContextAccessor();

            services.AddIdentityServer()
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityConfig.GetClients())
            .AddInMemoryApiScopes(IdentityConfig.GetScopes())
            .AddDeveloperSigningCredential(false)
            .AddResourceOwnerValidator <ResourceOwnerPasswordValidator>()
            .AddProfileService <CustomProfileService>();

            services.AddLogging(builder =>
            {
                builder.AddConsole();
            });

            services.AddScoped <ITokenProvider, TokenProvider>();
        }
Ejemplo n.º 17
0
        public void ConfigureServices(IServiceCollection services)
        {
            //configuração de contexto
            services.AddDbContext <CodenationContext>();
            //adicionar scoped interfaces - services - classe de validação de senha e usuário
            services.AddScoped <IResourceOwnerPasswordValidator, PasswordValidatorService>();
            services.AddScoped <IProfileService, UserProfileService>();
            //start classe identityconfig
            var builder = services.AddIdentityServer()
                          .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
                          .AddInMemoryApiResources(IdentityConfig.GetApis())
                          .AddInMemoryClients(IdentityConfig.GetClients())
                          .AddProfileService <UserProfileService>();

            //ambiente
            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("ambiente de produção precisa de chave real");
            }
        }
Ejemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            //注入IdentityServer4
            services.AddIdentityServer(c =>
            {
                //登陆地址
                c.UserInteraction.LoginUrl = "/Account/Login";
            })
            .AddDeveloperSigningCredential()

            //下面是注入资源信息
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            .AddInMemoryClients(IdentityConfig.GetClients())
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources());

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Ejemplo n.º 19
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            IFreeSql freeSql = new FreeSql.FreeSqlBuilder()
                               .UseConnectionString(FreeSql.DataType.SqlServer, Configuration.GetConnectionString("meta"))
                               .Build();

            services.AddSingleton(freeSql);
            services.AddSingleton <IAdminService, AdminService>();
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => false;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });


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

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityConfig.GetClients())
            /* .AddTestUsers(TestUsers.Users)*/;
        }
Ejemplo n.º 20
0
        public void ConfigureServices(IServiceCollection services)
        {
            var appConfig = _configuration.GetSection(nameof(AppConfig)).Get <AppConfig>() ?? new AppConfig();

            services.AddSingleton(Options.Create(appConfig));

            services.AddRazorPages();
            services.Configure <RouteOptions>(options =>
            {
                options.LowercaseUrls = true;
            });

            services.AddDatabaseDeveloperPageExceptionFilter();
            services.AddDbContext <AppDbContext>(options =>
            {
                options.UseNpgsql(_configuration.GetConnectionString("Postgres"), o => o.UseNodaTime());
            });

            services.AddIdentity <User, Role>()
            .AddEntityFrameworkStores <AppDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                options.User.RequireUniqueEmail        = true;
                options.User.AllowedUserNameCharacters = AppConfig.Policies.Slug.AllowedCharacters;
            });

            services.AddTransient <IUserValidator <User>, CustomUserNamePolicy>();

            var oAuthClientConfig = _configuration.Get <OAuthClientConfig>() ?? new OAuthClientConfig();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.ErrorUrl = "/errors/500";
                options.KeyManagement.KeyPath    = Path.Join(appConfig.ProtectedDataDir, "keys");
            })
            .AddAspNetIdentity <User>()
            .AddProfileService <CustomProfileService>()
            .AddOperationalStore <AppDbContext>()
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryClients(IdentityConfig.GetClients(_environment, appConfig, oAuthClientConfig.OAuthClients));

            services.ConfigureApplicationCookie(options =>
            {
                options.LoginPath          = "/login";
                options.LogoutPath         = "/logout";
                options.AccessDeniedPath   = "/errors/403";
                options.ReturnUrlParameter = "returnurl";
            });

            var authenticationBuilder = services.AddAuthentication();
            var oAuthProviderConfig   = _configuration.Get <OAuthProviderConfig>();

            if (oAuthProviderConfig?.OAuthProviders?.Any() == true)
            {
                if (oAuthProviderConfig !.OAuthProviders !.TryGetValue("GitHub", out var gitHubCredentials))
                {
                    authenticationBuilder.AddGitHub(options =>
                    {
                        options.ClientId     = gitHubCredentials.ClientId;
                        options.ClientSecret = gitHubCredentials.ClientSecret;
                        options.Scope.Add("user:email");
                    });
                }

                if (oAuthProviderConfig !.OAuthProviders !.TryGetValue("Discord", out var discordCredentials))
                {
                    authenticationBuilder.AddDiscord(options =>
                    {
                        options.ClientId     = discordCredentials.ClientId;
                        options.ClientSecret = discordCredentials.ClientSecret;
                        options.Scope.Add("email");
                    });
                }
            }

            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                                         builder.AllowAnyHeader()
                                         .AllowAnyMethod()
                                         .AllowCredentials()
                                         .Let(b => _environment.IsProduction()
                            ? b.WithOrigins($"{appConfig.ApiUri.Scheme}://{appConfig.ApiUri.Authority}")
                            : b.WithOrigins($"{appConfig.ApiUri.Scheme}://{appConfig.ApiUri.Authority}",
                                            "https://api.local.factorio.tech", "https://localhost:5101")));
            });

            services.AddApplicationInsightsTelemetry(options =>
            {
                options.ApplicationVersion = BuildInformation.Version;
            });

            services.AddSingleton <ITelemetryInitializer, CloudRoleInitializer>();
            services.AddSingleton <ITelemetryInitializer, UserInitializer>();

            if (!_environment.IsProduction())
            {
                services.AddTransient <DevDataSeeder>();
            }

            if (!_environment.IsDevelopment())
            {
                services.AddDataProtection()
                .PersistKeysToFileSystem(new DirectoryInfo(Path.Join(appConfig.ProtectedDataDir, "dataprotection")))
                .ProtectKeysWithCertificate(new X509Certificate2("/mnt/keys/certificate.pfx"));
            }

            services.AddTransient <DevDataSeeder>();
            services.AddTransient <CustomProfileService>();
        }
Ejemplo n.º 21
0
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(this.environment.ContentRootPath, "oauth_sign.pfx"), "abc234"); // put own signed certificate here
            var appSettingsSection = this.Configuration.GetSection("Settings");

            services.AddDbContext <ClientDbContext>(options =>
                                                    options.UseSqlServer(this.Configuration.GetConnectionString("ClientDataStore")));

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <IAuthServerDataProtectionProvider, AuthServerDataProtectionProvider>();

            services.AddIdentity <AuthUser, AuthRole>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequireLowercase       = true;
                options.Password.RequireUppercase       = true;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
            })
            .AddTokenProvider <AuthServerTokenProvider <AuthUser> >(TokenOptions.DefaultProvider)
            .AddUserStore <AuthUserStore>()
            .AddRoleStore <AuthRoleStore>();

            // for the UI
            services
            .AddMvc()
            .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver())
            .AddRazorOptions(razor =>
            {
                razor.ViewLocationExpanders.Add(new CustomViewLocationExpander());
            });

            // App Services
            services.Configure <ForwardedHeadersOptions>(options =>
            {
                options.ForwardedHeaders = ForwardedHeaders.XForwardedProto;
            });

            services.Configure <AuthAppSettings>(appSettingsSection);
            services.Configure <AuthServerSettings>(this.Configuration.GetSection("AuthorizationServer"));
            services.Configure <EmailServiceSetup>(this.Configuration.GetSection("EmailService"));
            services.AddTransient <IProfileService, IdentityProfileService>();
            services.AddTransient <IUserRepository, UserRepository>();
            services.AddTransient <IStatusRepository, StatusRepository>();
            services.AddTransient <IClientRepository, ClientRepository>();
            // services.AddTransient<IClientEmailService, SomeMailService>(); // TODO
            services.AddTransient <IAuthUserManager, AuthUserManager>();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl   = "/ui/login";
                options.UserInteraction.LogoutUrl  = "/ui/logout";
                options.UserInteraction.ConsentUrl = "/ui/consent";
                options.UserInteraction.ErrorUrl   = "/ui/error";
            })
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(IdentityConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityConfig.GetApiResources())
            //.AddInMemoryScopes(Scopes.Get())
            .AddInMemoryClients(IdentityConfig.GetClients(appSettingsSection["RedirectUri"], appSettingsSection["LogoutRedirectUri"]))
            .AddAspNetIdentity <AuthUser>()
            .AddProfileService <IdentityProfileService>();
        }