예제 #1
0
        public async Task InvokeAsync(HttpContext context,
                                      IAuthenticationSchemeProvider schemeProvider,
                                      IOptionsMonitorCache <FakeAuthenticationSchemeOptions> optionsCache)
        {
            var fakeOptions = context.RequestServices
                              .GetRequiredService <IOptionsSnapshot <FakeAuthenticationOptions> >().Value;

            foreach (var fakeScheme in fakeOptions.Schemes)
            {
                if (await schemeProvider.GetSchemeAsync(fakeScheme.SchemeName) != null)
                {
                    schemeProvider.RemoveScheme(fakeScheme.SchemeName);
                    optionsCache.TryRemove(fakeScheme.SchemeName);
                    var scheme = new AuthenticationScheme(fakeScheme.SchemeName,
                                                          fakeScheme.SchemeName,
                                                          typeof(FakeAuthenticationHandler));
                    schemeProvider.AddScheme(scheme);
                    var fakeSchemeOptions = new FakeAuthenticationSchemeOptions();
                    foreach (var claim in fakeScheme.Claims)
                    {
                        fakeSchemeOptions.Claims.Add(claim);
                    }
                    optionsCache.TryAdd(fakeScheme.SchemeName, fakeSchemeOptions);
                }
            }
            await _next(context);
        }
예제 #2
0
        public async Task <IActionResult> AddOrUpdate(string scheme, string optionsMessage)
        {
            if (await _schemeProvider.GetSchemeAsync(scheme) == null)
            {
                _schemeProvider.AddScheme(new AuthenticationScheme(scheme, scheme, typeof(GoogleHandler)));
            }
            else
            {
                _optionsCache.TryRemove(scheme);
            }
            _optionsCache.TryAdd(scheme, new GoogleOptions
            {
                SignInScheme = "Kalle",
                ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com",
                ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh"
                               //DisplayMessage = optionsMessage
            });

            //var a = await this._schemeProvider.GetSchemeAsync("Google");

            //return this.Challenge(new AuthenticationProperties
            //{

            //}, "Google");

            return(Redirect("/"));
        }
예제 #3
0
        private void CreateHttpClientFactoryOptions(UpstreamRequestSenderSettings settings)
        {
            httpFactoryOptionsMonitorCache.TryRemove(settings.HttpClientName);

            var options = new HttpClientFactoryOptions();

            options.HttpMessageHandlerBuilderActions.Add(builder => ConfigureHttpMessageHandlerBuilder(builder, settings));

            httpFactoryOptionsMonitorCache.TryAdd(settings.HttpClientName, options);
        }
예제 #4
0
        /// <summary>
        /// Tries to adds a new option to the cache, will return false if the name already exists.
        /// </summary>
        /// <param name="name">The name of the options instance.</param>
        /// <param name="options">The options instance.</param>
        /// <returns>Whether anything was added.</returns>
        public bool TryAdd(string name, AuthenticationSchemeOptions options)
        {
            var result = _parent.TryAdd(name, (TOptions)options);

            _onAdded.Invoke(name, options as TOptions);
            foreach (var postConfigure in _postConfigures)
            {
                postConfigure.PostConfigure(name, options as TOptions);
            }
            return(result);
        }
예제 #5
0
        public void Register(AuthenticationProvider provider)
        {
            _providerId    = provider.Id.ToString();
            _providerCache = new ProviderCache();
            SchemeName     = provider.Name;
            var scheme = new AuthenticationScheme(SchemeName, provider.DisplayName, typeof(NegotiateHandler));

            _schemeProvider.AddScheme(scheme);
            var options = new NegotiateOptions();

            _optionsCache.TryAdd(SchemeName, options);
        }
        public TOptions CreateOptions(string schemeName)
        {
            ArgumentValidation.ValidateString(nameof(schemeName), schemeName);

            var options = _optionsFactory.Create(schemeName);

            _optionsMonitorCache.TryRemove(schemeName);
            _optionsMonitorCache.TryAdd(schemeName, options);

            PostConfigure(schemeName, options);

            return(options);
        }
예제 #7
0
 public async Task <IActionResult> AddOrUpdate(string scheme, string optionsMessage)
 {
     if (await _schemeProvider.GetSchemeAsync(scheme) == null)
     {
         _schemeProvider.AddScheme(new AuthenticationScheme(scheme, scheme, typeof(SimpleAuthHandler)));
     }
     else
     {
         _optionsCache.TryRemove(scheme);
     }
     _optionsCache.TryAdd(scheme, new SimpleOptions {
         DisplayMessage = optionsMessage
     });
     return(Redirect("/"));
 }
예제 #8
0
        public IActionResult AddOpenIdConnect()
        {
            _schemeProvider.AddScheme(new AuthenticationScheme("oidc", "OpenID Connect", typeof(OpenIdConnectHandler)));
            var options = new OpenIdConnectOptions
            {
                MetadataAddress = "https://XXX/.well-known/openid-configuration",
                ClientId        = "XXX",
                ClientSecret    = "XXX",
                CallbackPath    = "/signin-oidc",
            };

            _openIdConnectPostConfigureOptions.PostConfigure("oidc", options);
            _openIdConnectOptionsCache.TryAdd("oidc", options);
            return(Redirect("/"));
        }
예제 #9
0
        private async Task AddScheme(ExternalLoginScheme scheme)
        {
            if (!new Regex("^Scheme[0-9]$").IsMatch(scheme.Name ?? string.Empty))
            {
                throw new ArgumentException($"Scheme name '{scheme.Name}' must be like '^Scheme[0-9]$'.");
            }
            if (await schemeProvider.GetSchemeAsync(scheme.Name) != null)
            {
                throw new ArgumentException($"Scheme '{scheme.Name}' already exists.");
            }
            if (!new Regex("^[ a-zA-Z0-9]+$").IsMatch(scheme.DisplayName ?? string.Empty))
            {
                throw new ArgumentException($"Scheme display name '{scheme.DisplayName}' must be like '^[ a-zA-Z0-9]+$'.");
            }

            var newOptions = new MicrosoftAccountOptions
            {
                SignInScheme          = IdentityServerConstants.ExternalCookieAuthenticationScheme,
                ClientId              = scheme.ClientId,
                ClientSecret          = scheme.ClientSecret,
                AuthorizationEndpoint = scheme.AuthorizationEndpoint,
                TokenEndpoint         = scheme.TokenEndpoint,
                CallbackPath          = scheme.CallbackPath,
            };

            newOptions.Validate();
            foreach (var c in optionsConfigure)
            {
                c.Configure(newOptions);
            }
            foreach (var c in optionsPostConfigure)
            {
                c.PostConfigure(scheme.Name, newOptions);
            }

            var dataProtector = newOptions.DataProtectionProvider.CreateProtector(typeof(CacheStateLocallyAndOnlySendReference).FullName, scheme.Name, "v1");

            newOptions.StateDataFormat = new CacheStateLocallyAndOnlySendReference(this.httpContextAccessor, dataProtector);

            optionsCache.TryAdd(scheme.Name, newOptions);
            schemeProvider.AddScheme(new AuthenticationScheme(scheme.Name, scheme.DisplayName, typeof(MicrosoftAccountHandler)));

            logger.LogInformation("Added external authentication {ExternalLogin} for tenant {Tenant}.", scheme.Name, resolvedTenant.TenantName);
        }
        public async Task <IActionResult> Add([FromBody] SchemeData schemeData)
        {
            var schemeName = string.Format("{0}_{1}", schemeData.Domain, schemeData.Scheme);

            if (schemeData.Scheme == "Google")
            {
                IOptionsMonitorCache <GoogleOptions> oAuthOptionsCache = serviceProvider.GetRequiredService <IOptionsMonitorCache <GoogleOptions> >();
                OAuthPostConfigureOptions <GoogleOptions, GoogleHandler> oAuthPostConfigureOptions = serviceProvider.GetRequiredService <OAuthPostConfigureOptions <GoogleOptions, GoogleHandler> >();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(GoogleHandler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }
                var options = new GoogleOptions
                {
                    ClientId     = "xxxxxxx",
                    ClientSecret = "xxxxxxxxxxxx"
                };
                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }
            else if (schemeData.Scheme == "Auth0")
            {
                IOptionsMonitorCache <Saml2Options> oAuthOptionsCache         = serviceProvider.GetRequiredService <IOptionsMonitorCache <Saml2Options> >();
                PostConfigureSaml2Options           oAuthPostConfigureOptions = serviceProvider.GetRequiredService <PostConfigureSaml2Options>();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(Saml2Handler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }
                //urn:ccidentity.auth0.com
                var options = new Saml2Options();
                options.SPOptions.EntityId   = new EntityId("https://localhost:44332/auth0");
                options.SPOptions.ModulePath = "/Saml2Auth0";
                options.SPOptions.MinIncomingSigningAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

                var idp = new IdentityProvider(new EntityId("urn:ccidentity.auth0.com"), options.SPOptions)
                {
                    MetadataLocation = "https://xxxxxxxx/samlp/metadata/7HmaqIPuC32Pc95e0clSqN3n3ogzkTkP",
                    LoadMetadata     = true,
                    AllowUnsolicitedAuthnResponse = true,
                    Binding = Saml2BindingType.HttpRedirect,
                    SingleSignOnServiceUrl = new Uri("https://xxxxxxx/samlp/7HmaqIPuC32Pc95e0clSqN3n3ogzkTkP"),
                };

                idp.SigningKeys.AddConfiguredKey(new X509Certificate2(Convert.FromBase64String("MIIDAzCCAeugAwIBAgIJLNhPpvvzUXRnMA0GCSqGSIb3DQEBCwUAMB8xHTAbBgNVBAMTFGNjaWRlbnRpdHkuYXV0aDAuY29tMB4XDTIwMDQwMTEwMTEzMVoXDTMzMTIwOTEwMTEzMVowHzEdMBsGA1UEAxMUY2NpZGVudGl0eS5hdXRoMC5jb20wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDXOaxVEhjYW+eT3YduAnRMGrJGcriVU1e3n3RXB6SPt4QsmXsOcdLItaqKthSKeRTkOtXvRANvve1YrEUeMwWzv9gsKoQrwM5fDKwG+chEJNxEZEtMmGfqasb++taLTduNPphSm1xs0RNHeeFXdJHt4QWVsCMJfH2RRUlRHaqj4niew/uzJOZNiWLnXp+03tiy5uwOyxyOhpMOX9QZqpSwHHzZ8OoLIIxynuSiWipZoeCoxrZKM3kHW9YlwLVZvcqAZhWTbut6sC+Y+1O1Sfh1tr6XxWzcP5GaMMV2xQPgPYYKjYMiMeFSe4E5P3R4QxmEoeOpAhWzHQbiyzMYLIO1AgMBAAGjQjBAMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFFldi8Vcq5IwPROX5ssxqm+uuQaZMA4GA1UdDwEB/wQEAwIChDANBgkqhkiG9w0BAQsFAAOCAQEA1DWRiUaTCHqPUQRzOOnuiSib2dga2Qd1v39dqaaHrLe345c0eo1yn0cE50xtSTlx++WeIQ3RbXCMm70Za3+AfQhTOisqiHS0Nb+ZrxkHFzl0JNgY4AHQFbYsM3QwZQLBjfhL3KyYoTiQRifn/L9N1F/ZJN5PatoybwwJAbo4V0Y1g9pMSWXhbUKJCBP3Eq/8LPx2erAs3RkheYtz+beviOiXNeNYvUNxmPNy+vpp/zvFG5q20vtK7a3EBbOh1pputoctmAfnGoyjZ06JDAa006iJiGwXlwNonBFClLwbds4H3fc9hv4RsCWlVVdcO+l5FL17nhMRYZUn74lGHOCMZg==")));

                options.IdentityProviders.Add(idp);

                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }
            else if (schemeData.Scheme == "Saml2")
            {
                IOptionsMonitorCache <Saml2Options> oAuthOptionsCache         = serviceProvider.GetRequiredService <IOptionsMonitorCache <Saml2Options> >();
                PostConfigureSaml2Options           oAuthPostConfigureOptions = serviceProvider.GetRequiredService <PostConfigureSaml2Options>();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(Saml2Handler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }

                var options = new Saml2Options();
                options.SPOptions.EntityId = new EntityId("https://localhost:44332/Saml2");
                options.SPOptions.MinIncomingSigningAlgorithm = "http://www.w3.org/2000/09/xmldsig#rsa-sha1";

                var idp = new IdentityProvider(new EntityId("https://xxxxxxxxxxxx/adfs/services/trust"), options.SPOptions)
                {
                    //MetadataLocation = "https://xxxxxxxxxxxx/FederationMetadata/2007-06/FederationMetadata.xml",
                    //LoadMetadata = true,
                    AllowUnsolicitedAuthnResponse = true,
                    Binding = Saml2BindingType.HttpRedirect,
                    SingleSignOnServiceUrl = new Uri("https://xxxxxxxxx/adfs/ls/"),
                };

                idp.SigningKeys.AddConfiguredKey(new X509Certificate2(Convert.FromBase64String("MIIC5jCCAc6gAwIBAgIQOMQMbu2YTpFIO7bLoDczgjANBgkqhkiG9w0BAQsFADAvMS0wKwYDVQQDEyRBREZTIFNpZ25pbmcgLSBEZXYtMTAxLkJhbmtPZlpvbmUubGswHhcNMjAwMzMwMTQyOTQ5WhcNMjEwMzMwMTQyOTQ5WjAvMS0wKwYDVQQDEyRBREZTIFNpZ25pbmcgLSBEZXYtMTAxLkJhbmtPZlpvbmUubGswggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQC0sv1rrY0QcVy8kCYz48dTE0qWlwg7J67kNDuO4um37DKnmSK43QTKMkN4Oe / q6 + a8YV2XW7aHqVzirdyeCWDqWf0fuef0jBhysylwdZI8P8PHAhX632jkQ9dXKqKC9kVEsV + LMzMB98xv3ue + rAjQMctrvdapTgvRTOyu5SEHV7zKN / AXDgqM1AT9ae4prRhg7F37Y6h4DVjCdOZgV7LpmgkkFxFnmk0G5il9yfFnLs2Xw3dQxh8HPj9XCgeNT3GGnui + d69BnESsWDjUBUuBGB / +6WQixC4SnKzbssVTy3W4h3aSSsGljAAJfh5YUafzqCjG7Z6xE16LNBieKjbVAgMBAAEwDQYJKoZIhvcNAQELBQADggEBAH / a2bttVBkWzk4Q7K8qjgC / GQboK1NJewEPdi + 8GKG5RD + hWWz /qmXKT0u6ZklzmNrsxj + jPxIOzlv7Aaa5CbGUHHRoG7mgWnvV7y0Qys3OfRUpIzOK0HzDhe / LlyHyX3TpKDH / b1YQJiE6yHgwEdkO4ZBQsOHDNm9pvWH2YJQqMFbWPA4ZeUASeUO0h + BdR4Fog / MYu86lensZwZUKbq / 1 + M5xao3LZfQh5oyEBpH0roRJOazjMSHV + U4sLdvkvXx6in4BLwt1HiMAm0oA6c + vSW5GANAJBXPupfP6Njt0lpGGC3bLgWOlU65NTPwIZhvAjs / gV / pBa + jVMVxDP0g = ")));

                options.IdentityProviders.Add(idp);

                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }
            else
            {
                IOptionsMonitorCache <FacebookOptions> oAuthOptionsCache = serviceProvider.GetRequiredService <IOptionsMonitorCache <FacebookOptions> >();
                OAuthPostConfigureOptions <FacebookOptions, FacebookHandler> oAuthPostConfigureOptions = serviceProvider.GetRequiredService <OAuthPostConfigureOptions <FacebookOptions, FacebookHandler> >();

                if (await schemeProvider.GetSchemeAsync(schemeName) == null)
                {
                    schemeProvider.AddScheme(new AuthenticationScheme(schemeName, schemeData.Scheme, typeof(FacebookHandler)));
                }
                else
                {
                    oAuthOptionsCache.TryRemove(schemeName);
                }
                var options = new FacebookOptions
                {
                    AppId     = "xxxxxxxxxxxx",
                    AppSecret = "xxxxxxxxxxxxxxxxx"
                };

                oAuthOptionsCache.TryAdd(schemeName, options);
                oAuthPostConfigureOptions.PostConfigure(schemeName, options);
                oAuthOptionsCache.TryAdd(schemeName, options);
            }

            return(Redirect("/"));
        }
예제 #11
0
        public async Task AddOrUpdate(string tenantId)
        {
            var scheme          = $"{tenantId}-scheme";
            var oidOptions      = new OpenIdConnectOptions();
            var samlOptions     = new Saml2pAuthenticationOptions();
            var saml2SpOptions  = new SpOptions();
            var saml2IdpOptions = new IdpOptions();
            var tenant          = _repo.GetAllTenants().FirstOrDefault(x => x.TenantId.Equals(tenantId));
            var oidcProtocol    = tenant.Protocol.Equals("oidc");

            if (tenant != null && oidcProtocol)
            {
                var oidConfig = _repo.GetOpenIdConfig(tenantId);
                oidOptions = BuildOidOptions(oidConfig);
            }
            else
            {
                var samlConfig = _repo.GetSamlConfig(tenantId);
                saml2SpOptions = new SpOptions()
                {
                    EntityId                   = "https://localhost:44374/saml",
                    SigningCertificate         = new X509Certificate2("testclient.pfx", "test"),
                    MetadataPath               = "/saml/metadata",
                    SignAuthenticationRequests = true
                };
                saml2IdpOptions = new IdpOptions()
                {
                    EntityId             = samlConfig.IdpEntityId,
                    SingleSignOnEndpoint = new SamlEndpoint(samlConfig.SingleSignOnEndpoint, SamlBindingTypes.HttpPost),
                    SingleLogoutEndpoint = new SamlEndpoint(samlConfig.SingleLogoutEndpoint, SamlBindingTypes.HttpPost),
                    SigningCertificate   = new X509Certificate2(samlConfig.IdpSigningCertificate), //file name
                };

                samlOptions = BuildSamlOptions(samlConfig, saml2SpOptions, saml2IdpOptions);
            }

            if (await _schemeProvider.GetSchemeAsync(scheme) == null)

            {
                _schemeProvider.AddScheme(new AuthenticationScheme(scheme, scheme, oidcProtocol ? typeof(OpenIdConnectHandler) : typeof(Saml2pAuthenticationHandler)));
            }
            else
            {
                if (oidcProtocol)
                {
                    _openIdOptions.TryRemove(scheme);
                }
                else
                {
                    _saml2pOptions.TryRemove(scheme);
                }
            }
            if (oidcProtocol)
            {
                _oidPostConfOptions.PostConfigure(scheme, oidOptions);
                _openIdOptions.TryAdd(scheme, oidOptions);
            }
            else
            {
                _saml2pOptions.TryAdd(scheme, samlOptions);
            }
        }