コード例 #1
0
        public void ConfigureServices(IServiceCollection services)
        {
            _clientId     = _configuration["MicrosoftClientId"];
            _clientSecret = _configuration["MircosoftClientSecret"];
            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            var x509Certificate2 = GetCertificate(_environment, _configuration);

            AddLocalizationConfigurations(services);

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

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

            services.AddAuthentication()
            //.AddMicrosoftAccount(options =>
            //{
            //    options.ClientId = _clientId;
            //    options.SignInScheme = "Identity.External";
            //    options.ClientSecret = _clientSecret;
            //})
            .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options =>      // Microsoft common
            {
                //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                options.ClientId     = _clientId;
                options.ClientSecret = _clientSecret;
                options.SignInScheme = "Identity.External";
                options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                options.ResponseType = "code";
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    NameClaimType  = "email",
                };
                options.CallbackPath = "/signin-microsoft";
                options.Prompt       = "login"; // login, consent
            });

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

            services.AddIdentityServer()
            .AddSigningCredential(x509Certificate2)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #2
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig = Configuration.GetSection("StsConfig");

            _clientId     = Configuration["MicrosoftClientId"];
            _clientSecret = Configuration["MircosoftClientSecret"];
            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.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder
                    .AllowCredentials()
                    .WithOrigins("https://localhost:44311", "https://localhost:44390", "https://localhost:44395", "https://localhost:44318")
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

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

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

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

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

            services.AddScoped <IUserClaimsPrincipalFactory <ApplicationUser>, AdditionalUserClaimsPrincipalFactory>();

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddSingleton <IAuthorizationHandler, IsAdminHandler>();

            services.AddAuthentication()
            .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.AddAuthorization(options =>
            {
                options.AddPolicy("IsAdmin", policyIsAdminRequirement =>
                {
                    policyIsAdminRequirement.Requirements.Add(new IsAdminRequirement());
                });
            });

            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"
                };

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

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

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #3
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            var x509Certificate2Certs = GetCertificates(_environment, _configuration)
                                        .GetAwaiter().GetResult();

            AddLocalizationConfigurations(services);

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

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2");

            services.AddAuthentication()
            .AddOpenIdConnect("aad", "Login with Azure AD", options =>      // Microsoft common
            {
                //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                options.ClientId     = "your_client_id";  // ADD APP Registration ID
                options.ClientSecret = "your_secret";     // ADD APP Registration secret
                options.SignInScheme = "Identity.External";
                options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                options.ResponseType = "code";
                options.UsePkce      = false; // live does not support this yet
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    // ALWAYS VALIDATE THE ISSUER IF POSSIBLE !!!!
                    ValidateIssuer = false,
                    // ValidIssuers = new List<string> { "tenant..." },
                    NameClaimType = "email",
                };
                options.CallbackPath = "/signin-microsoft";
                options.Prompt       = "login"; // login, consent
            });

            services.AddAntiforgery(options =>
            {
                options.SuppressXFrameOptionsHeader = true;
                options.Cookie.SameSite             = SameSiteMode.Strict;
                options.Cookie.SecurePolicy         = CookieSecurePolicy.Always;
            });

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

            var stsConfig = _configuration.GetSection("StsConfig");

            var identityServer = services.AddIdentityServer()
                                 .AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
                                 .AddInMemoryIdentityResources(Config.GetIdentityResources())
                                 .AddInMemoryApiResources(Config.GetApiResources())
                                 .AddInMemoryClients(Config.GetClients(stsConfig))
                                 .AddAspNetIdentity <ApplicationUser>()
                                 .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            if (x509Certificate2Certs.SecondaryCertificate != null)
            {
                identityServer.AddValidationKey(x509Certificate2Certs.SecondaryCertificate);
            }

            services.Configure <Fido2Configuration>(_configuration.GetSection("fido2"));
            services.AddScoped <Fido2Storage>();
            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout         = TimeSpan.FromMinutes(2);
                options.Cookie.HttpOnly     = true;
                options.Cookie.SameSite     = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            });
        }
コード例 #4
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

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

            var x509Certificate2 = GetCertificates(_environment, Configuration).GetAwaiter().GetResult();

            AddLocalizationConfigurations(services);

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder
                    .AllowCredentials()
                    .WithOrigins(
                        "https://localhost:44311",
                        "https://localhost:44352",
                        "https://localhost:44372",
                        "https://localhost:44378",
                        "https://localhost:44390")
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

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

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

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

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2");

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.AddAntiforgery(options =>
            {
                options.SuppressXFrameOptionsHeader = true;
                options.Cookie.SameSite             = SameSiteMode.Strict;
                options.Cookie.SecurePolicy         = CookieSecurePolicy.Always;
            });

            services.AddAuthentication()
            .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.AddAuthorization();

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

            services.AddIdentityServer()
            .AddSigningCredential(x509Certificate2.ActiveCertificate)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.Configure <Fido2Configuration>(Configuration.GetSection("fido2"));
            services.Configure <Fido2MdsConfiguration>(Configuration.GetSection("fido2mds"));
            services.AddScoped <Fido2Storage>();
            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout         = TimeSpan.FromMinutes(2);
                options.Cookie.HttpOnly     = true;
                options.Cookie.SameSite     = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            });
        }
コード例 #5
0
        public void ConfigureServices(IServiceCollection services)
        {
            _clientId     = _configuration["MicrosoftClientId"];
            _clientSecret = _configuration["MircosoftClientSecret"];
            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            var x509Certificate2Certs = GetCertificates(_environment, _configuration)
                                        .GetAwaiter().GetResult();

            AddLocalizationConfigurations(services);

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

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2");

            services.AddAuthentication()
            //.AddMicrosoftAccount(options =>
            //{
            //    options.ClientId = _clientId;
            //    options.SignInScheme = "Identity.External";
            //    options.ClientSecret = _clientSecret;
            //})
            .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options =>      // Microsoft common
            {
                //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                options.ClientId     = _clientId;
                options.ClientSecret = _clientSecret;
                options.SignInScheme = "Identity.External";
                options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                options.ResponseType = "code";
                options.UsePkce      = true;
                options.Scope.Add("profile");
                options.Scope.Add("email");
                options.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuer = false,
                    NameClaimType  = "email",
                };
                options.CallbackPath = "/signin-microsoft";
                options.Prompt       = "login"; // login, consent
            });

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

            //RsaSecurityKey rsaSecurityKey =
            //    new RsaSecurityKey(x509Certificate2Certs.ActiveCertificate.GetRSAPrivateKey());

            ECDsaSecurityKey eCDsaSecurityKey
                = new ECDsaSecurityKey(x509Certificate2Certs.ActiveCertificate.GetECDsaPrivateKey());

            services.AddIdentityServer()
            //.AddSigningCredential(x509Certificate2)
            .AddSigningCredential(eCDsaSecurityKey, "ES384")     // ecdsaCertificate
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.Configure <Fido2Configuration>(_configuration.GetSection("fido2"));
            services.AddScoped <Fido2Storage>();
            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout         = TimeSpan.FromMinutes(2);
                options.Cookie.HttpOnly     = true;
                options.Cookie.SameSite     = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            });
        }
コード例 #6
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig = _configuration.GetSection("StsConfig");

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            _clientId     = _configuration["MicrosoftClientId"];
            _clientSecret = _configuration["MircosoftClientSecret"];
            var authConfigurations    = _configuration.GetSection("AuthConfigurations");
            var useLocalCertStore     = Convert.ToBoolean(_configuration["UseLocalCertStore"]);
            var certificateThumbprint = _configuration["CertificateThumbprint"];

            var x509Certificate2Certs = GetCertificates(_environment, _configuration)
                                        .GetAwaiter().GetResult();

            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlServer(_configuration.GetConnectionString("DefaultConnection")));


            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();
            AddLocalizationConfigurations(services);
            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders()
            .AddTokenProvider <Fifo2UserTwoFactorTokenProvider>("FIDO2");

            if (_clientId != null)
            {
                services.AddAuthentication()
                .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options =>  // Microsoft common
                {
                    //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                    options.ClientId     = _clientId;
                    options.ClientSecret = _clientSecret;
                    options.SignInScheme = "Identity.External";
                    options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                    options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                    options.ResponseType = "code";
                    options.UsePkce      = false; // live does not support this yet
                    options.Scope.Add("profile");
                    options.Scope.Add("email");
                    options.ClaimActions.MapUniqueJsonKey("preferred_username", "preferred_username");
                    options.ClaimActions.MapAll();  // ClaimActions.MapUniqueJsonKey("amr", "amr");
                    //options.ClaimActions.Remove("amr");
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.TokenValidationParameters     = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        NameClaimType  = "email",
                    };
                    options.CallbackPath = "/signin-microsoft";
                    options.Prompt       = "login"; // login, consent
                    options.Events       = new OpenIdConnectEvents
                    {
                        OnRedirectToIdentityProvider = context =>
                        {
                            context.ProtocolMessage.SetParameter("acr_values", "mfa");

                            return(Task.FromResult(0));
                        }
                    };
                });
            }
            else
            {
                services.AddAuthentication();
            }

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

            services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
            .AddSigningCredential(x509Certificate2Certs.ActiveCertificate)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryApiScopes(Config.GetApiScopes())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();

            services.Configure <Fido2Configuration>(_configuration.GetSection("fido2"));
            services.Configure <Fido2MdsConfiguration>(_configuration.GetSection("fido2mds"));
            services.AddScoped <Fido2Storage>();
            // Adds a default in-memory implementation of IDistributedCache.
            services.AddDistributedMemoryCache();
            services.AddSession(options =>
            {
                options.IdleTimeout         = TimeSpan.FromMinutes(2);
                options.Cookie.HttpOnly     = true;
                options.Cookie.SameSite     = SameSiteMode.None;
                options.Cookie.SecurePolicy = CookieSecurePolicy.Always;
            });
        }
コード例 #7
0
        public void ConfigureServices(IServiceCollection services)
        {
            _clientId     = Configuration["MicrosoftClientId"];
            _clientSecret = Configuration["MircosoftClientSecret"];
            var authConfigurations    = Configuration.GetSection("AuthConfigurations");
            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, "sts_dev_cert.pfx"), "1234");
            }

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

            services.Configure <AuthConfigurations>(Configuration.GetSection("AuthConfigurations"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

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

            if (_clientId != null)
            {
                services.AddAuthentication()
                .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options =>  // Microsoft common
                {
                    //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                    options.ClientId     = _clientId;
                    options.ClientSecret = _clientSecret;
                    options.SignInScheme = "Identity.External";
                    options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                    options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                    options.ResponseType = "code";
                    options.Scope.Add("profile");
                    options.Scope.Add("email");
                    options.TokenValidationParameters = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        NameClaimType  = "email",
                    };
                    options.CallbackPath = "/signin-microsoft";
                    options.Prompt       = "login"; // login, consent
                });
            }
            else
            {
                services.AddAuthentication();
            }

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

            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")
                };

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

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

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

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

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(authConfigurations))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #8
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseNpgsql(Configuration.GetConnectionString("DefaultConnection")));

            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddSingleton <LocService>();
            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .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: "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()
            .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.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));
                };
            });

            services.AddTransient <IEmailSender, EmailSender>();

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

            var builder = services.AddIdentityServer(options =>
            {
                options.Events.RaiseErrorEvents       = true;
                options.Events.RaiseInformationEvents = true;
                options.Events.RaiseFailureEvents     = true;
                options.Events.RaiseSuccessEvents     = true;
            })
                          .AddInMemoryIdentityResources(Config.GetIdentityResources())
                          .AddInMemoryApiResources(Config.GetApiResources())
                          .AddInMemoryClients(Config.GetClients())
                          .AddAspNetIdentity <ApplicationUser>();

            if (Environment.IsDevelopment())
            {
                builder.AddDeveloperSigningCredential();
            }
            else
            {
                throw new Exception("need to configure key material");
            }
        }
コード例 #9
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig     = Configuration.GetSection("StsConfig");
            var _clientId     = Configuration["MicrosoftClientId"];
            var _clientSecret = Configuration["MircosoftClientSecret"];

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

            services.Configure <StsConfig>(Configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();
            services.AddSingleton <IAuthorizationHandler, IsAdminHandler>();

            X509Certificate2 cert = GetCertificate(_environment, Configuration);

            AddLocalizationConfigurations(services);

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder
                    .AllowCredentials()
                    .WithOrigins("https://localhost:44311", "https://localhost:44390", "https://localhost:44395", "https://localhost:44318")
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

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

            services.AddScoped <IUserClaimsPrincipalFactory <ApplicationUser>, AdditionalUserClaimsPrincipalFactory>();

            services.AddAuthentication()
            .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.AddAuthorization(options =>
            {
                options.AddPolicy("IsAdmin", policyIsAdminRequirement =>
                {
                    policyIsAdminRequirement.Requirements.Add(new IsAdminRequirement());
                });
            });

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

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #10
0
ファイル: Startup.cs プロジェクト: BionStt/ApiJwtWithTwoSts
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <StsConfig>(_configuration.GetSection("StsConfig"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.MinimumSameSitePolicy = SameSiteMode.Unspecified;
                options.OnAppendCookie        = cookieContext =>
                                                CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
                options.OnDeleteCookie = cookieContext =>
                                         CheckSameSite(cookieContext.Context, cookieContext.CookieOptions);
            });

            var x509Certificate2 = GetCertificate(_environment, _configuration);

            AddLocalizationConfigurations(services);

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

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

            services.AddAuthentication()
            .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.AddControllersWithViews(options =>
            {
                options.Filters.Add(new SecurityHeadersAttribute());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    var assemblyName = new AssemblyName(typeof(SharedResource).GetTypeInfo().Assembly.FullName);
                    return(factory.Create("SharedResource", assemblyName.Name));
                };
            });

            var stsConfig = _configuration.GetSection("StsConfig");

            services.AddIdentityServer()
            .AddSigningCredential(x509Certificate2)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #11
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            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, "sts_dev_cert.pfx"), "1234");
            }

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

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

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

            // TODO: Google Auth Config:
            services.AddAuthentication()
            .AddGoogle(options =>
            {
                options.ClientId     = "[ClientId]";
                options.ClientSecret = "[ClientSecret]";
            });

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

            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")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                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));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients())
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #12
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.ConfigureApplicationCookie(options =>
            {
                options.Cookie.SecurePolicy = Microsoft.AspNetCore.Http.CookieSecurePolicy.Always;
            });

            _clientId     = Configuration["MicrosoftClientId"];
            _clientSecret = Configuration["MircosoftClientSecret"];
            var authConfigurations    = Configuration.GetSection("AuthConfigurations");
            var useLocalCertStore     = Convert.ToBoolean(Configuration["UseLocalCertStore"]);
            var certificateThumbprint = Configuration["CertificateThumbprint"];

            X509Certificate2 cert = GetCertificate(_environment, Configuration);

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

            services.Configure <AuthConfigurations>(Configuration.GetSection("AuthConfigurations"));
            services.Configure <EmailSettings>(Configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            AddLocalizationConfigurations(services);

            if (_clientId != null)
            {
                services.AddAuthentication()
                .AddOpenIdConnect("Azure AD / Microsoft", "Azure AD / Microsoft", options =>  // Microsoft common
                {
                    //  https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration
                    options.ClientId     = _clientId;
                    options.ClientSecret = _clientSecret;
                    options.SignInScheme = "Identity.External";
                    options.RemoteAuthenticationTimeout = TimeSpan.FromSeconds(30);
                    options.Authority    = "https://login.microsoftonline.com/common/v2.0/";
                    options.ResponseType = "code";
                    options.UsePkce      = false; // live does not support this yet
                    options.Scope.Add("profile");
                    options.Scope.Add("email");
                    options.ClaimActions.MapUniqueJsonKey("preferred_username", "preferred_username");
                    options.ClaimActions.MapAll();  // ClaimActions.MapUniqueJsonKey("amr", "amr");
                    //options.ClaimActions.Remove("amr");
                    options.GetClaimsFromUserInfoEndpoint = true;
                    options.TokenValidationParameters     = new TokenValidationParameters
                    {
                        ValidateIssuer = false,
                        NameClaimType  = "email",
                    };
                    options.CallbackPath = "/signin-microsoft";
                    options.Prompt       = "login"; // login, consent
                    options.Events       = new OpenIdConnectEvents
                    {
                        OnRedirectToIdentityProvider = context =>
                        {
                            context.ProtocolMessage.SetParameter("acr_values", "mfa");

                            return(Task.FromResult(0));
                        }
                    };
                });
            }
            else
            {
                services.AddAuthentication();
            }

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

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

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(authConfigurations))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #13
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig = Configuration.GetSection("StsConfig");

            X509Certificate2 cert;

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

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

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

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

            services.AddAuthentication()
            .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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddDefaultTokenProviders();

            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")
                };

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

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

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

            services.AddMvc().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));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #14
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            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, "sts_dev_cert.pfx"), "1234");
            }

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

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

            services.AddTransient <IEndSessionRequestValidator, MyEndSessionRequestValidator>();

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

            services.AddAuthentication()
            .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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .AddErrorDescriber <StsIdentityErrorDescriber>()
            .AddDefaultTokenProviders();

            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")
                };

                options.DefaultRequestCulture = new RequestCulture(culture: "de-DE", uiCulture: "de-DE");
                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));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            var migrationsAssembly = typeof(Startup).GetTypeInfo().Assembly.GetName().Name;

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>()
            .AddOperationalStore(options =>
            {
                options.ConfigureDbContext = builder =>
                                             builder.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"),
                                                                  sql => sql.MigrationsAssembly(migrationsAssembly));

                // this enables automatic token cleanup. this is optional.
                options.EnableTokenCleanup   = true;
                options.TokenCleanupInterval = 30;      // interval in seconds
            });
        }
コード例 #15
0
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <AuthConfiguration>(_configuration.GetSection("AuthConfiguration"));
            services.Configure <AuthSecretsConfiguration>(_configuration.GetSection("AuthSecretsConfiguration"));
            services.Configure <EmailSettings>(_configuration.GetSection("EmailSettings"));
            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();
            services.AddTransient <IEmailSender, EmailSender>();

            var authConfiguration        = _configuration.GetSection("AuthConfiguration");
            var authSecretsConfiguration = _configuration.GetSection("AuthSecretsConfiguration");

            var clientId     = _configuration["MicrosoftClientId"];
            var clientSecret = _configuration["MircosoftClientSecret"];

            var sharedResourceAssemblyName = SharedResourceAssemblyName;
            var x509Certificate2           = GetCertificate(_environment, _configuration);
            var vueJsApiUrl = authConfiguration["VueJsApiUrl"];

            services.AddCors(options =>
            {
                options.AddPolicy("AllowAllOrigins",
                                  builder =>
                {
                    builder
                    .AllowCredentials()
                    .WithOrigins(vueJsApiUrl)
                    .SetIsOriginAllowedToAllowWildcardSubdomains()
                    .AllowAnyHeader()
                    .AllowAnyMethod();
                });
            });

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

            services.AddSingleton <LocService>();
            AddLocalizationConfigurations(services, sharedResourceAssemblyName);

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

            // services.AddAuthorization();     => Don't need this as it is include with .AddControllersWithViews

            services.AddAuthentication()
            .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.AddControllersWithViews(options =>
            {
                options.Filters.Add(new SecurityHeadersAttribute());
            })
            .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
            .AddViewLocalization()
            .AddDataAnnotationsLocalization(options =>
            {
                options.DataAnnotationLocalizerProvider = (type, factory) =>
                {
                    return(factory.Create("SharedResource", sharedResourceAssemblyName));
                };
            });

            services.AddRazorPages();

            services.AddIdentityServer()
            .AddSigningCredential(x509Certificate2)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources(authSecretsConfiguration))
            .AddInMemoryClients(Config.GetClients(authConfiguration))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }
コード例 #16
0
        public void ConfigureServices(IServiceCollection services)
        {
            var stsConfig             = Configuration.GetSection("StsConfig");
            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.AddDbContext <ApplicationDbContext>(options =>
                                                         options.UseSqlite(Configuration.GetConnectionString("DefaultConnection")));

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

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

            services.AddAuthentication()
            .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.AddIdentity <ApplicationUser, IdentityRole>()
            .AddEntityFrameworkStores <ApplicationDbContext>()
            .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
                {
                    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().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));
                };
            });

            services.AddTransient <IProfileService, IdentityWithAdditionalClaimsProfileService>();

            services.AddTransient <IEmailSender, EmailSender>();

            services.AddIdentityServer()
            .AddSigningCredential(cert)
            .AddInMemoryIdentityResources(Config.GetIdentityResources())
            .AddInMemoryApiResources(Config.GetApiResources())
            .AddInMemoryClients(Config.GetClients(stsConfig))
            .AddAspNetIdentity <ApplicationUser>()
            .AddProfileService <IdentityWithAdditionalClaimsProfileService>();
        }