private static void AddLocalizationConfigurations(IServiceCollection services)
    {
        services.AddSingleton <LocService>();
        services.AddLocalization(options => options.ResourcesPath = "Resources");

        services.Configure <RequestLocalizationOptions>(
            options =>
        {
            var supportedCultures = new List <CultureInfo>
            {
                new CultureInfo("en-US"),
                new CultureInfo("de-DE"),
                new CultureInfo("de-CH"),
                new CultureInfo("it-IT"),
                new CultureInfo("gsw-CH"),
                new CultureInfo("fr-FR"),
                new CultureInfo("zh-Hans"),
                new CultureInfo("ga-IE"),
                new CultureInfo("es-MX")
            };

            options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
            options.SupportedCultures     = supportedCultures;
            options.SupportedUICultures   = supportedCultures;

            var providerQuery = new LocalizationQueryProvider
            {
                QueryParameterName = "ui_locales"
            };

            options.RequestCultureProviders.Insert(0, providerQuery);
        });
    }
示例#2
0
        public static void AddMvcLocalization(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddLocalization(opts => opts.ResourcesPath = ConfigurationConsts.ResourcesPath);
            services.Configure <EmailSettings>(configuration.GetSection("EmailSettings"));
            services.AddSingleton <LocService>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new SecurityHeadersAttribute());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });
        }
示例#3
0
 public static IServiceCollection AddLocalizationConfigurations(this IServiceCollection services)
 {
     services.AddSingleton <LocService>();
     services.AddLocalization(options => options.ResourcesPath = "Resources");
     services.Configure <RequestLocalizationOptions>(
         options =>
     {
         var supportedCultures = new List <CultureInfo> {
             new CultureInfo("en-US"), new CultureInfo("es-MX")
         };
         options.DefaultRequestCulture = new RequestCulture(culture: "es-MX", uiCulture: "es-MX");
         options.SupportedCultures     = supportedCultures;
         options.SupportedUICultures   = supportedCultures;
         var providerQuery             = new LocalizationQueryProvider {
             QueryParameterName = "ui_locales"
         };
         options.RequestCultureProviders.Insert(0, providerQuery);
     });
     return(services);
 }
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            string configsConnectionString;
            string usersConnectionString;

            if (env == "Development")
            {
                usersConnectionString   = "Server=localhost;Database=microstarter.identity_users;Username=doom;Password=machine";
                configsConnectionString = "Server=localhost;Database=microstarter.identity_config;Username=doom;Password=machine";
            }
            else // if (env == "Docker_Production")
            {
                usersConnectionString   = "Server=postgre_name;Database=microstarter.identity_users;Username=doom;Password=machine";
                configsConnectionString = "Server=postgre_name;Database=microstarter.identity_config;Username=doom;Password=machine";
            }
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <UserDbContext>(options =>
                                                  options.UseNpgsql(usersConnectionString,
                                                                    sql => sql.MigrationsAssembly(migrationsAssembly))
                                                  );
            services.AddIdentity <ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores <UserDbContext>();

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

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseSuccessEvents     = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
            })
            .AddDeveloperSigningCredential()
            // .AddTestUsers(TestUsers.Users)
            .AddAspNetIdentity <ApplicationUser>()
            // You can Configure Profile Service for your needs
            .AddProfileService <AuthProfileService>()
            // this adds the config data from DB (clients, resources, CORS)
            .AddConfigurationStore(options =>
            {
                options.ResolveDbContextOptions = (provider, builder) =>
                {
                    builder.UseNpgsql(configsConnectionString,
                                      sql => sql.MigrationsAssembly(migrationsAssembly));
                };
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = (builder) =>
                {
                    builder.UseNpgsql(configsConnectionString,
                                      sql => sql.MigrationsAssembly(migrationsAssembly));
                };
                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                // options.TokenCleanupInterval = 10; // interval in seconds, short for testing
            })
            .AddConfigurationStoreCache();



            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddScoped <ClientIdFilter>();
            services.AddScoped <ClientSelector>();

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ClientViewLocationExpander());
            });

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                // Cookie is required for the logout, query parameters at not supported with the endsession endpoint
                // Only works in the same domain
                var providerCookie = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                // options.RequestCultureProviders.Insert(0, providerCookie);
                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc()
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            return(services.BuildServiceProvider(validateScopes: false));
        }
示例#5
0
        public void ConfigureServices(IServiceCollection services)
        {
            var cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDbContext <ConfigurationStoreContext>(options =>
                                                              options.UseSqlite(
                                                                  Configuration.GetConnectionString("ConfigurationStoreConnection"),
                                                                  b => b.MigrationsAssembly("AspNetCoreIdentityServer4")
                                                                  )
                                                              );

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddScoped <ClientIdFilter>();
            services.AddScoped <ClientSelector>();
            services.AddAuthentication();

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ClientViewLocationExpander());
            });

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-CH", uiCulture: "de-CH");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                // Cookie is required for the logout, query parameters at not supported with the endsession endpoint
                // Only works in the same domain
                var providerCookie = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                // options.RequestCultureProviders.Insert(0, providerCookie);
                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc()
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

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

            services.AddCors(options =>
            {
                options.AddPolicy("AllowSpecificOrigin",
                                  builder => builder.WithOrigins("*")
                                  .WithHeaders("*")
                                  .WithMethods("*")
                                  .WithExposedHeaders("*"));
            });

            services.AddTransient <IClientStore, ClientStore>();
            services.AddTransient <IResourceStore, ResourceStore>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddResourceStore <ResourceStore>()
            .AddClientStore <ClientStore>()
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            //.AddInMemoryIdentityResources(Config.GetIdentityResources())
            //.AddInMemoryApiResources(Config.GetApiResources())
            //.AddInMemoryClients(Config.GetClients());
        }
        public override void ConfigureCustomServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            var redisConfig           = Configuration.GetSection("RedisConfig");
            var clientConfig          = Configuration.GetSection("ClientSetting").Get <List <ClientSetting> >();
            var openIdConnectConfig   = Configuration.GetSection("OpenIdConnectSettings").Get <OpenIdConnectSettings>();
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;



            cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "aggregator.pfx"), "test");

            services.AddDbContext <UsersDbContext>(options =>
                                                   options.UseNpgsql(Configuration.GetConnectionString("UsersDb")));

            services.AddDbContext <AuthorizationDbContext>();

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.Configure <List <ClientSetting> >(Configuration.GetSection("ClientSetting"));

            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = true;
                options.Password.RequiredLength         = 8;
                options.Password.RequireLowercase       = true;
                options.Password.RequireNonAlphanumeric = true;
                options.Password.RequireUppercase       = true;
            });

            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddApiVersioning(o =>
            {
                o.ApiVersionReader = new UrlSegmentApiVersionReader();
                o.AssumeDefaultVersionWhenUnspecified = true;
                o.DefaultApiVersion = ApiVersion.Default;
            });
            IdentityModelEventSource.ShowPII = true;
            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = "Bearer";
                options.DefaultChallengeScheme    = "oidc";
            }).AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme  = openIdConnectConfig.SignInScheme;
                options.SignOutScheme = IdentityServerConstants.SignoutScheme;

                options.Authority            = openIdConnectConfig.Authority;
                options.RequireHttpsMetadata = false;

                options.ClientId = clientConfig.First(x => x.ClientId == "back_office_web").ClientId;

                options.SaveTokens           = true;
                options.SignedOutRedirectUri = "http://localhost:8080";
            }).AddIdentityServerAuthentication(options =>
            {
                options.Authority            = openIdConnectConfig.Authority;
                options.RequireHttpsMetadata = false;

                options.ApiName       = "credit_life";
                options.EnableCaching = true;
                options.CacheDuration = TimeSpan.FromMinutes(10); // that's the default
            });



            services.AddCors(options =>
            {
                options.AddDefaultPolicy(builder =>
                {
                    builder.AllowAnyHeader();
                    builder.AllowAnyMethod();
                    builder.WithExposedHeaders();
                    builder.AllowCredentials();
                    builder.SetIsOriginAllowed(s =>
                    {
                        foreach (var item in clientConfig)
                        {
                            if (item.AllowedCorsOrigins.Any(x => x == s))
                            {
                                return(true);
                            }
                        }

                        return(false);
                    });
                });
            });

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <UsersDbContext>()
            .AddDefaultTokenProviders();

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH"),
                    new CultureInfo("it-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-CH", uiCulture: "de-CH");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParameterName = "ui_locales"
                };

                // Cookie is required for the logout, query parameters at not supported with the endsession endpoint
                // Only works in the same domain
                var providerCookie = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                // options.RequestCultureProviders.Insert(0, providerCookie);
                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc(options =>
            {
                options.Filters.Add(new ActionFilterDispatcher(_container.GetAllInstances));
            }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1)

            .AddJsonOptions(options =>
            {
                options.SerializerSettings.DateFormatHandling = DateFormatHandling.IsoDateFormat;
            })
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer(options =>
            {
                options.IssuerUri    = stsConfig["IssuerUrl"];
                options.PublicOrigin = options.IssuerUri;
            })
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddOperationalStore(options =>
            {
                options.RedisConnectionString = redisConfig["Url"];
                options.Db = 1;
            })
            .AddRedisCaching(options =>
            {
                options.RedisConnectionString = redisConfig["Url"];
                options.KeyPrefix             = "idsrv";
            })
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(clientConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.AddSwaggerGen(options =>
            {
                options.DescribeAllEnumsAsStrings();
                options.SwaggerDoc("v1", new Swashbuckle.AspNetCore.Swagger.Info
                {
                    Title   = "HTTP API",
                    Version = "v1"
                });

                // UseFullTypeNameInSchemaIds replacement for .NET Core
                options.CustomSchemaIds(x => x.FullName);
            });
        }
示例#7
0
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            string env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            string configsConnectionString;
            string usersConnectionString;
            string rabbitHostString;

            if (env == "Development")
            {
                usersConnectionString   = "Server=localhost;Database=microstarter.identity_users;Username=doom;Password=machine";
                configsConnectionString = "Server=localhost;Database=microstarter.identity_config;Username=doom;Password=machine";
                rabbitHostString        = "rabbitmq://localhost";
            }
            else // if (env == "Docker_Production")
            {
                usersConnectionString   = "Server=postgre_name;Database=microstarter.identity_users;Username=doom;Password=machine";
                configsConnectionString = "Server=postgre_name;Database=microstarter.identity_config;Username=doom;Password=machine";
                rabbitHostString        = "rabbitmq://MicroStarterEventBus";
            }
            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddDbContext <UserDbContext>(options =>
                                                  options.UseNpgsql(usersConnectionString,
                                                                    sql => sql.MigrationsAssembly(migrationsAssembly))
                                                  );
            services.AddIdentity <ApplicationUser, ApplicationRole>()
            .AddEntityFrameworkStores <UserDbContext>();

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

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseSuccessEvents     = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
            })
            .AddDeveloperSigningCredential()
            // .AddTestUsers(TestUsers.Users)
            .AddAspNetIdentity <ApplicationUser>()
            // You can Configure Profile Service for your needs
            .AddProfileService <AuthProfileService>()
            // this adds the config data from DB (clients, resources, CORS)
            .AddConfigurationStore(options =>
            {
                options.ResolveDbContextOptions = (provider, builder) =>
                {
                    builder.UseNpgsql(configsConnectionString,
                                      sql => sql.MigrationsAssembly(migrationsAssembly));
                };
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = (builder) =>
                {
                    builder.UseNpgsql(configsConnectionString,
                                      sql => sql.MigrationsAssembly(migrationsAssembly));
                };
                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                // options.TokenCleanupInterval = 10; // interval in seconds, short for testing
            })
            .AddConfigurationStoreCache();



            services.AddMassTransit(p => {
                // p.AddConsumer<SomeEventHappenedConsumer>();
            });
            var _retryCount = 8;
            var policy      = RetryPolicy.Handle <SocketException>()
                              .Or <BrokerUnreachableException>()
                              .Or <RabbitMqConnectionException>()
                              .OrInner <BrokerUnreachableException>()
                              .OrInner <RabbitMqConnectionException>()
                              .WaitAndRetry(_retryCount, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (ex, time) =>
            {
                Console.WriteLine("Could not connect Broker Trying Again");
                Console.WriteLine(ex);
                Console.WriteLine("Retrying RabbitMq Connection");
            }
                                            );
            IServiceProvider prov = services.BuildServiceProvider();
            IBusControl      busControl;

            policy.Execute(() =>
            {
                busControl = Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    var host = cfg.Host(new Uri(rabbitHostString), "/", h => {
                        h.Username("doom");
                        h.Password("machine");
                    });

                    cfg.ReceiveEndpoint(host, e =>
                    {
                        e.PrefetchCount = 8;
                        // Add Your Event Consumers Here
                        // If you want Inject services to consumer, pass provider param
                        // e.Consumer<SomeEventHappenedConsumer>(provider)
                    });
                });
                services.AddSingleton(provider => busControl);
            });
            services.AddSingleton <IPublishEndpoint>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <ISendEndpointProvider>(provider => provider.GetRequiredService <IBusControl>());
            services.AddSingleton <IBus>(provider => provider.GetRequiredService <IBusControl>());
            // Register with IHostedService To Start bus in Application Start
            services.AddSingleton <Microsoft.Extensions.Hosting.IHostedService, BusService>();
            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");
            services.AddScoped <ClientIdFilter>();
            services.AddScoped <ClientSelector>();

            services.Configure <RazorViewEngineOptions>(options =>
            {
                options.ViewLocationExpanders.Add(new ClientViewLocationExpander());
            });

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en-US"),
                    new CultureInfo("de-CH"),
                    new CultureInfo("fr-CH")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QureyParamterName = "ui_locales"
                };

                // Cookie is required for the logout, query parameters at not supported with the endsession endpoint
                // Only works in the same domain
                var providerCookie = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                // options.RequestCultureProviders.Insert(0, providerCookie);
                options.RequestCultureProviders.Insert(0, providerQuery);
            });

            services.AddMvc()
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            return(services.BuildServiceProvider(validateScopes: false));
        }