Example #1
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("AllowAll",
                                                          builder =>
                                                          builder
                                                          .AllowAnyMethod()
                                                          .AllowAnyOrigin()
                                                          .AllowAnyHeader()));


            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.AddDbContext <SecurityDbContext>(options =>
            {
                var provider = Configuration.GetSection("EfProvider").Get <string>();
                switch (provider)
                {
                case "MySql":
                    options.UseMySql(
                        Configuration.GetConnectionString("Auth_MySql"));
                    return;

                case "SqlServer":
                    options.UseSqlServer(
                        Configuration.GetConnectionString("Auth_SqlServer"));
                    return;

                default:
                    throw new NotImplementedException($"The provider {provider} is not implemented yet.");
                }
            });
            services.AddIdentity <User, Role>()
            .AddEntityFrameworkStores <SecurityDbContext>()
            .AddDefaultTokenProviders();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
            services.AddScoped <IEmailSender, FakeEmailSender>();

            var clients = Configuration.GetSection("Clients").Get <IEnumerable <ClientInfo> >();

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Identity/Account/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients(clients))
            .AddAspNetIdentity <User>();
        }
Example #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options => options.AddPolicy("AllowAll",
                                                          builder =>
                                                          builder
                                                          .AllowAnyMethod()
                                                          .AllowAnyOrigin()
                                                          .AllowAnyHeader()));

            foreach (var pair in Configuration.AsEnumerable())
            {
                Console.WriteLine($"{pair.Key}:{pair.Value}");
            }

            var provider = Configuration.GetSection("EfProvider").Get <string>();

            if (string.IsNullOrWhiteSpace(provider))
            {
                Console.WriteLine("Error: database provider is not set, the expected name is: EfProvider");
            }
            var connectionString = Configuration.GetConnectionString("Auth");

            if (string.IsNullOrWhiteSpace(connectionString))
            {
                Console.WriteLine("Error: Connection string is not set, the expected name is: Auth");
            }

            switch (provider)
            {
            case "MySql":
                services.AddDbContext <SecurityDbContext, SecurityDbContext_MySql>(
                    options => options.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString),
                                                x => x.MigrationsAssembly(typeof(SecurityDbContext_MySql).Assembly.GetName().Name)
                                                .MigrationsHistoryTable(HistoryRepository.DefaultTableName.ToLowerInvariant())));
                break;

            case "SqlServer":
                services.AddDbContext <SecurityDbContext>(options => options.UseSqlServer(connectionString));
                break;

            case "PostgreSql":
            case "PostgreSQL":
                services.AddDbContext <SecurityDbContext, SecurityDbContext_PostgreSql>(options => options.UseNpgsql(connectionString));
                break;

            default:
                throw new NotImplementedException($"The provider {provider} is not implemented yet.");
            }

            services.Configure <ConfigModel>(Configuration.GetSection("Config"));
            var config = Configuration.GetSection("Config").Get <ConfigModel>();

            services.AddIdentity <User, Role>(options =>
            {
                options.Password.RequireDigit           = config?.Password?.RequireDigit ?? true;
                options.Password.RequireLowercase       = config?.Password?.RequireLowercase ?? true;
                options.Password.RequireNonAlphanumeric = config?.Password?.RequireNonAlphanumeric ?? true;
                options.Password.RequireUppercase       = config?.Password?.RequireUppercase ?? true;
                options.Password.RequiredLength         = config?.Password?.RequiredLength ?? 6;
                options.Password.RequiredUniqueChars    = config?.Password?.RequiredUniqueChars ?? 1;
                options.SignIn.RequireConfirmedEmail    = config?.SignIn?.RequireConfirmedEmail ?? false;
            })
            .AddEntityFrameworkStores <SecurityDbContext>()
            .AddDefaultTokenProviders();

            if (string.IsNullOrWhiteSpace(config?.Email?.Server))
            {
                services.AddScoped <IEmailSender, FakeEmailSender>();
            }
            else
            {
                services.AddTransient <IEmailSender, SmtpEmailSender>();
            }

            services.Configure <IdentityOptions>(options =>
            {
                options.Password.RequireDigit           = config?.Password?.RequireDigit ?? true;
                options.Password.RequireLowercase       = config?.Password?.RequireLowercase ?? true;
                options.Password.RequireNonAlphanumeric = config?.Password?.RequireNonAlphanumeric ?? true;
                options.Password.RequireUppercase       = config?.Password?.RequireUppercase ?? true;
                options.Password.RequiredLength         = config?.Password?.RequiredLength ?? 6;
                options.Password.RequiredUniqueChars    = config?.Password?.RequiredUniqueChars ?? 1;
            });

            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.SameSite = SameSiteMode.None;
            });

            services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme)
            .AddCookie("Cookies", options =>
            {
                options.Cookie.SameSite = SameSiteMode.None;
            });

            services.AddRazorPages();

            var clients = Configuration.GetSection("Clients").Get <IEnumerable <ClientInfo> >();

            services.AddSingleton(clients);
            Console.WriteLine();
            Console.WriteLine("Clients");
            Console.WriteLine("==================");
            Console.WriteLine(JsonConvert.SerializeObject(clients));
            Console.WriteLine("==================");

            services.AddIdentityServer(options =>
            {
                options.UserInteraction.LoginUrl  = "/Identity/Account/Login";
                options.UserInteraction.LogoutUrl = "/Identity/Account/Logout";
            })
            .AddDeveloperSigningCredential()
            .AddInMemoryPersistedGrants()
            .AddInMemoryIdentityResources(IdentityServerConfig.GetIdentityResources())
            .AddInMemoryApiResources(IdentityServerConfig.GetApiResources())
            .AddInMemoryClients(IdentityServerConfig.GetClients(clients))
            .AddAspNetIdentity <User>();
        }