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

            services.AddDataProtection()
            .SetApplicationName("identity-server")
            .PersistKeysToFileSystem(new DirectoryInfo(@"/var/dpkeys/"));

            services.Configure <MongoDBSettings>(options =>
            {
                options.ConnectionString
                    = $"mongodb://{Environment.GetEnvironmentVariable("MONGODB_USERNAME")}:{Environment.GetEnvironmentVariable("MONGODB_PASSWORD")}@{Environment.GetEnvironmentVariable("COMPANY_MONGODB_HOST")}:{Environment.GetEnvironmentVariable("COMPANY_MONGODB_PORT")}";
                options.Database
                    = $"{Environment.GetEnvironmentVariable("COMPANY_MONGODB_DATABASE_NAME")}";
            });

            services.AddIdentityWithMongoStoresUsingCustomTypes <ApplicationUser, ApplicationUserRole>($"mongodb://{Environment.GetEnvironmentVariable("MONGODB_USERNAME")}:{Environment.GetEnvironmentVariable("MONGODB_PASSWORD")}@{Environment.GetEnvironmentVariable("USER_MONGODB_HOST")}:{Environment.GetEnvironmentVariable("USER_MONGODB_PORT")}/{Environment.GetEnvironmentVariable("USER_MONGODB_DATABASE_NAME")}")
            .AddDefaultTokenProviders();

            services.Configure <IdentityOptions>(options =>
            {
                // Password settings
                options.Password.RequireDigit           = false;
                options.Password.RequiredLength         = 6;
                options.Password.RequireNonAlphanumeric = false;
                options.Password.RequireUppercase       = false;
                options.Password.RequireLowercase       = false;
                options.Password.RequiredUniqueChars    = 5;

                options.User.RequireUniqueEmail = true;
                //options.SignIn.RequireConfirmedEmail = true;

                options.Tokens.EmailConfirmationTokenProvider = "Phone";
            });
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            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.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("vi-VN"),
                    new CultureInfo("en-US")
                };

                options.DefaultRequestCulture = new RequestCulture("vi-VN");
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;

                var providerQuery = new LocalizationQueryProvider
                {
                    QueryParameterName = "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.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            var dict = new Dictionary <string, string>
            {
                { "ConnectionString", $"mongodb://{Environment.GetEnvironmentVariable("MONGODB_USERNAME")}:{Environment.GetEnvironmentVariable("MONGODB_PASSWORD")}@{Environment.GetEnvironmentVariable("IDENTITYSERVER_MONGODB_HOST")}:{Environment.GetEnvironmentVariable("IDENTITYSERVER_MONGODB_PORT")}" },
                { "Database", $"{Environment.GetEnvironmentVariable("IDENTITYSERVER_MONGODB_DATABASE_NAME")}" }
            };
            var cfgbuilder = new ConfigurationBuilder();

            cfgbuilder.AddInMemoryCollection(dict);
            var identityServerConfig = cfgbuilder.Build();

            services.AddIdentityServer()
            .AddConfigurationStore(identityServerConfig)
            .AddOperationalStore(identityServerConfig)
            .AddDeveloperSigningCredential()
            .AddExtensionGrantValidator <Extensions.ExtensionGrantValidator>()
            .AddExtensionGrantValidator <Extensions.NoSubjectExtensionGrantValidator>()
            .AddJwtBearerClientAuthentication()
            .AddAppAuthRedirectUriValidator()
            .AddAspNetIdentity <ApplicationUser>().AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.AddExternalIdentityProviders();

            var builder = new ContainerBuilder();
            var timeout = TimeSpan.FromSeconds(10);

            builder.Register(c => new MessageRequestClient <ICreateCompany, Company>(c.Resolve <IBus>(), new Uri($"rabbitmq://{Environment.GetEnvironmentVariable("RABBITMQ_HOST")}/create_company"), timeout))
            .As <IRequestClient <ICreateCompany, Company> >()
            .SingleInstance();
            builder.Register(c => new MessageRequestClient <IUploadLogoCompany, Company>(c.Resolve <IBus>(), new Uri($"rabbitmq://{Environment.GetEnvironmentVariable("RABBITMQ_HOST")}/upload_logo_company"), timeout))
            .As <IRequestClient <IUploadLogoCompany, Company> >()
            .SingleInstance();
            builder.Register(c => new MessageRequestClient <ICountSendActiveAccount, ISendActiveAccountCounted>(c.Resolve <IBus>(), new Uri($"rabbitmq://{Environment.GetEnvironmentVariable("RABBITMQ_HOST")}/count_send_active_account"), timeout))
            .As <IRequestClient <ICountSendActiveAccount, ISendActiveAccountCounted> >()
            .SingleInstance();

            builder.Register(c =>
            {
                return(Bus.Factory.CreateUsingRabbitMq(sbc =>
                                                       sbc.Host(new Uri($"rabbitmq://{Environment.GetEnvironmentVariable("RABBITMQ_HOST")}/"), h =>
                {
                    h.Username(Environment.GetEnvironmentVariable("RABBITMQ_USERNAME"));
                    h.Password(Environment.GetEnvironmentVariable("RABBITMQ_PASSWORD"));
                })
                                                       ));
            })
            .As <IBus>()
            .As <IBusControl>()
            .As <IPublishEndpoint>()
            .SingleInstance();
            builder.Populate(services);

            builder.RegisterType <EmailSender>().As <IEmailSender>()
            .WithParameter("sendGridUser", "apikey")
            .WithParameter("sendGridKey", "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");

            builder.RegisterType <SMSSender>().As <ISMSSender>();

            ApplicationContainer = builder.Build();
            return(new AutofacServiceProvider(ApplicationContainer));
        }
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)
        {
            //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;
            //});


            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert;

            if (_environment.IsProduction())
            {
                if (useLocalCertStore)
                {
                    using (X509Store store = new X509Store(StoreName.My, StoreLocation.LocalMachine))
                    {
                        store.Open(OpenFlags.ReadOnly);
                        var certs = store.Certificates.Find(X509FindType.FindByThumbprint, certificateThumbprint, false);
                        cert = certs[0];
                        store.Close();
                    }
                }
                else
                {
                    // Azure deployment, will be used if deployed to Azure
                    var vaultConfigSection = Configuration.GetSection("Vault");
                    var keyVaultService    = new KeyVaultCertificateService(vaultConfigSection["Url"], vaultConfigSection["ClientId"], vaultConfigSection["ClientSecret"]);
                    cert = keyVaultService.GetCertificateFromKeyVault(vaultConfigSection["CertificateName"]);
                }
            }
            else
            {
                cert = new X509Certificate2(Path.Combine(_environment.ContentRootPath, "damienbodserver.pfx"), "");
            }

            services.Configure <GeneralConfig>(Configuration.GetSection("GeneralConfig"));

            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.Configure <SmtpEmailSettings>(Configuration.GetSection("SmtpEmailSettings"));
            services.AddSingleton <SmtpClient>((serviceProvider) =>
            {
                var config = serviceProvider.GetRequiredService <IConfiguration>();
                return(new SmtpClient()
                {
                    Host = config.GetValue <String>("SmtpEmailSettings:Host"),
                    Port = config.GetValue <int>("SmtpEmailSettings:Port"),
                    Credentials = new NetworkCredential(
                        config.GetValue <String>("SmtpEmailSettings:Username"),
                        config.GetValue <String>("SmtpEmailSettings:Password")
                        ),
                    EnableSsl = true,
                    DeliveryMethod = SmtpDeliveryMethod.Network
                });
            });

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

            string connectionString   = Configuration.GetConnectionString("DefaultConnection");
            var    migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

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

            services.AddIdentity <ApplicationUser, IdentityRole>(
                config =>
            {
                config.SignIn.RequireConfirmedEmail    = true;
                config.Password.RequireDigit           = false;
                config.Password.RequiredLength         = 7;
                config.Password.RequireLowercase       = false;
                config.Password.RequireNonAlphanumeric = false;
                config.Password.RequireUppercase       = false;
            })
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            var guestPolicy = new AuthorizationPolicyBuilder()
                              .RequireAuthenticatedUser()
                              .RequireClaim("scope", "dataEventRecords")
                              .Build();

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.Configure <IISOptions>(iis =>
            {
                iis.AuthenticationDisplayName = "Windows";
                iis.AutomaticAuthentication   = false;
            });

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddSigningCredential(cert)
            .AddAspNetIdentity <ApplicationUser>()
            // this adds the config data from DB (clients, resources)
            .AddConfigurationStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(connectionString,
                                                            sql => sql.MigrationsAssembly(migrationsAssembly));
            })
            // this adds the operational data from DB (codes, tokens, consents)
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = b =>
                                             b.UseSqlServer(connectionString,
                                                            sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup = true;
                // options.TokenCleanupInterval = 15; // frequency in seconds to cleanup stale grants. 15 is useful during debugging
            })
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            //services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
            //  .AddIdentityServerAuthentication(options =>
            //  {
            //      options.Authority = Config.HOST_URL + "/";
            //      options.ApiName = "dataEventRecords";
            //      options.ApiSecret = "dataEventRecordsSecret";
            //      options.SupportedTokens = SupportedTokens.Both;
            //  });

            //JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();

            services.AddTransient <IEmailSender, EmailSender>();

            //IdentityServerAuthenticationOptions identityServerValidationOptions = new IdentityServerAuthenticationOptions
            //{
            //    Authority = Config.HOST_URL + "/",
            //    AllowedScopes = new List<string> { "dataEventRecords" },
            //    ApiSecret = "dataEventRecordsSecret",
            //    ApiName = "dataEventRecords",
            //    AutomaticAuthenticate = true,
            //    SupportedTokens = SupportedTokens.Both,
            //    // TokenRetriever = _tokenRetriever,
            //    // required if you want to return a 403 and not a 401 for forbidden responses
            //    AutomaticChallenge = true,
            //};

            //app.UseIdentityServerAuthentication(identityServerValidationOptions);

            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");
                });
                options.AddPolicy("dataEventRecords", policyUser =>
                {
                    policyUser.RequireClaim("scope", "dataEventRecords");
                });
            });


            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com";
                options.ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh";
            });
            //.AddOpenIdConnect("oidc", "OpenID Connect", options =>
            //{
            //    options.Authority = "https://demo.identityserver.io/";
            //    options.ClientId = "implicit";
            //    options.SaveTokens = true;

            //    options.TokenValidationParameters = new TokenValidationParameters
            //    {
            //        NameClaimType = "name",
            //        RoleClaimType = "role"
            //    };
            //}).AddOpenIdConnect("aad", "Login with Azure AD", options =>
            //{
            //    options.Authority = $"https://login.microsoftonline.com/common";
            //    options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false };
            //    options.ClientId = "99eb0b9d-ca40-476e-b5ac-6f4c32bfb530";
            //    options.CallbackPath = "/signin-oidc";
            //});

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

            services.Configure <RequestLocalizationOptions>(
                options =>
            {
                var supportedCultures = new List <CultureInfo>
                {
                    new CultureInfo("ar"),
                    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"
                };

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

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