Example #1
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.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddAuthentication();

            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 requestProvider = options.RequestCultureProviders.OfType <AcceptLanguageHeaderRequestCultureProvider>().First();
                options.RequestCultureProviders.Clear();
                var provider = new LocalizationCookieProvider
                {
                    CookieName = "defaultLocale"
                };
                options.RequestCultureProviders.Insert(0, provider);
            });

            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.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
        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));
        }
Example #3
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);
            });
        }
Example #5
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));
        }
Example #6
0
        public virtual void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(
                                                             Configuration.GetConnectionString("DefaultConnection")));

            services.AddDefaultIdentity <ApplicationUser>(options => options.SignIn.RequireConfirmedAccount = false)
            .AddEntityFrameworkStores <ApplicationDbContext>();

            services.AddIdentityServer().AddApiAuthorization <ApplicationUser, ApplicationDbContext>();

            services.AddAuthentication().AddIdentityServerJwt();

            services.AddControllersWithViews().AddNewtonsoftJson().AddJsonOptions(options =>
                                                                                  options.JsonSerializerOptions.Converters.Add(new JsonStringEnumConverter()));

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

            // Configure localization / culture to translate Razor Pages
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("en"),
                    new CultureInfo("es"),
                    new CultureInfo("pl")
                };

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

                options.RequestCultureProviders.Clear();
                var provider = new LocalizationCookieProvider
                {
                    CookieName = "language"
                };
                options.RequestCultureProviders.Insert(0, provider);
            });

            // DI - Repositories
            services.AddScoped <IEventRepository, EventRepository>();

            // DI - Services
            services.AddScoped <IEventService, EventService>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IEmailService, EmailService>();
            services.AddScoped <INotificationService, NotificationService>();

            // E-mail connection metadata
            var connectionMetadata = Configuration.GetSection("ConnectionMetadata").Get <ConnectionMetadata>();

            services.AddSingleton(connectionMetadata);

            // Localization service
            services.AddSingleton <LocalizationService>();

            // Quartz services
            services.AddSingleton <IJobFactory, SingletonJobFactory>();
            services.AddSingleton <ISchedulerFactory, StdSchedulerFactory>();
            services.AddHostedService <QuartzHostedService>();

            // Job and schedule for sending notifications
            services.AddSingleton <NotificationsJob>();
            services.AddSingleton(new JobSchedule(
                                      typeof(NotificationsJob),
                                      Configuration.GetValue <string>("NotificationsCronExpression")));

            // Adding AutoMapper ( ModelMapper from Utils )
            services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());

            // In production, the Angular files will be served from this directory
            services.AddSpaStaticFiles(configuration => configuration.RootPath = "ClientApp/dist");
        }
Example #7
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddLocalization(options => options.ResourcesPath = "resources");

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

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

                options.RequestCultureProviders.Clear();
                var provider = new LocalizationCookieProvider
                {
                    CookieName = "i18next"
                };
                options.RequestCultureProviders.Insert(0, provider);
            });
            // Add framework services.
            services.AddDbContext <DatabaseContext>(options =>
                                                    options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity <User, IdentityRole>()
            .AddEntityFrameworkStores <DatabaseContext>()
            .AddDefaultTokenProviders();

            services.AddMvc();

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

            services.AddIdentityServer()
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(Configuration.GetValue <string>("IdentityServerUrl")))
            .AddAspNetIdentity <User>()
            .AddProfileService <IdentityProfileService>();


            // Add external authentication middleware below. To configure them please see http://go.microsoft.com/fwlink/?LinkID=532715

            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "998042782978-s07498t8i8jas7npj4crve1skpromf37.apps.googleusercontent.com";
                options.ClientSecret = "HsnwJri_53zn7VcO1Fm7THBb";
            });

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();



            services.AddAuthentication(options =>
            {
                options.DefaultScheme          = "Cookies";
                options.DefaultChallengeScheme = "oidc";
            })
            .AddCookie("Cookies")
            .AddOpenIdConnect("oidc", options =>
            {
                options.SignInScheme = "Cookies";

                options.Authority            = Configuration.GetValue <string>("IdentityServerUrl");
                options.RequireHttpsMetadata = false;

                options.ClientId     = "mvc";
                options.ClientSecret = "secret";
                options.ResponseType = "code id_token";

                options.SaveTokens = true;
                options.GetClaimsFromUserInfoEndpoint = true;

                options.Scope.Add("api1");
                options.Scope.Add("offline_access");
            });

            services.AddAuthorization(options =>
            {
                options.AddPolicy("dataEventRecordsAdmin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "dataEventRecords.admin");
                });
                options.AddPolicy("admin", policyAdmin =>
                {
                    policyAdmin.RequireClaim("role", "admin");
                });
                options.AddPolicy("dataEventRecordsUser", policyUser =>
                {
                    policyUser.RequireClaim("role", "dataEventRecords.user");
                });
            });

            services.AddAuthentication("Bearer")
            .AddIdentityServerAuthentication(options =>
            {
                options.Authority            = Configuration.GetValue <string>("IdentityServerUrl");
                options.RequireHttpsMetadata = false;

                options.ApiName = "api1";
            });
            services.AddApiVersioning(o =>
            {
                o.ReportApiVersions = true;
                o.AssumeDefaultVersionWhenUnspecified = true;
            });

            //services.UseCookieAuthentication(new CookieAuthenticationOptions
            //{
            //});

            //services.UseOpenIdConnectAuthentication(new OpenIdConnectOptions
            //{
            //    SignInScheme = "Cookies",

            //    Authority = "http://localhost:5000",
            //    RequireHttpsMetadata = false,

            //    ClientId = "mvc",
            //    ClientSecret = "secret",

            //    ResponseType = "code id_token",
            //    Scope = { "api1", "offline_access" },

            //    GetClaimsFromUserInfoEndpoint = true,
            //    SaveTokens = true
            //});
        }