Esempio n. 1
0
        /*****************************************/
        /* helper APIs for the AccountController */
        /*****************************************/
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                var vm = new LoginViewModel
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    Username         = context?.LoginHint,
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } };
                }

                return(vm);
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null)
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.Client.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
Esempio n. 2
0
        /*****************************************/
        /* helper APIs for the AccountController */
        /*****************************************/

        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                var vm = new LoginViewModel
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    Username         = context?.LoginHint,
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } };
                }

                return(vm);
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null)
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.Client.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            if (context != null)
            {
                var authClient = SqlHelper.Query <AuthClient>($"SELECT * FROM AuthClients WHERE ClientId='{context.Client.ClientId}'", connectionString).FirstOrDefault();

                var authorityName    = config.GetValue <string>("AuthorityName");
                var ssoAuthorityName = authorityName;

                return(new LoginViewModel
                {
                    AllowRememberLogin = AccountOptions.AllowRememberLogin,
                    EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = providers.ToArray(),
                    ClientDisplayName = authClient.ClientName,
                    ClientIcon = authClient.Logo,
                    IsBeta = authClient.IsBeta,
                    Is3rdParty = authClient.Is3rdParty,
                    SingleSignOnAuthorityName = ssoAuthorityName,
                    IsActive = authClient.IsActive
                });
            }
            return(null);
        }
Esempio n. 3
0
        public async Task <IActionResult> PreValidate(string domainHint)
        {
            IActionResult invalidJson(string errorMessageKey, Exception ex = null)
            {
                Response.StatusCode = ex == null ? 400 : 500;
                return(Json(new ErrorResponseModel(_i18nService.T(errorMessageKey))
                {
                    ExceptionMessage = ex?.Message,
                    ExceptionStackTrace = ex?.StackTrace,
                    InnerExceptionMessage = ex?.InnerException?.Message,
                }));
            }

            try
            {
                // Validate domain_hint provided
                if (string.IsNullOrWhiteSpace(domainHint))
                {
                    return(invalidJson("NoOrganizationIdentifierProvidedError"));
                }

                // Validate organization exists from domain_hint
                var organization = await _organizationRepository.GetByIdentifierAsync(domainHint);

                if (organization == null)
                {
                    return(invalidJson("OrganizationNotFoundByIdentifierError"));
                }
                if (!organization.UseSso)
                {
                    return(invalidJson("SsoNotAllowedForOrganizationError"));
                }

                // Validate SsoConfig exists and is Enabled
                var ssoConfig = await _ssoConfigRepository.GetByIdentifierAsync(domainHint);

                if (ssoConfig == null)
                {
                    return(invalidJson("SsoConfigurationNotFoundForOrganizationError"));
                }
                if (!ssoConfig.Enabled)
                {
                    return(invalidJson("SsoNotEnabledForOrganizationError"));
                }

                // Validate Authentication Scheme exists and is loaded (cache)
                var scheme = await _schemeProvider.GetSchemeAsync(organization.Id.ToString());

                if (scheme == null || !(scheme is IDynamicAuthenticationScheme dynamicScheme))
                {
                    return(invalidJson("NoSchemeOrHandlerForSsoConfigurationFoundError"));
                }

                // Run scheme validation
                try
                {
                    await dynamicScheme.Validate();
                }
                catch (Exception ex)
                {
                    var translatedException = _i18nService.GetLocalizedHtmlString(ex.Message);
                    var errorKey            = "InvalidSchemeConfigurationError";
                    if (!translatedException.ResourceNotFound)
                    {
                        errorKey = ex.Message;
                    }
                    return(invalidJson(errorKey, translatedException.ResourceNotFound ? ex : null));
                }
            }
            catch (Exception ex)
            {
                return(invalidJson("PreValidationError", ex));
            }

            // Everything is good!
            return(new EmptyResult());
        }
Esempio n. 4
0
    private async Task BuildModelAsync(string returnUrl)
    {
        Input = new InputModel
        {
            ReturnUrl = returnUrl
        };

        var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

        if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
        {
            var local = context.IdP == Duende.IdentityServer.IdentityServerConstants.LocalIdentityProvider;

            // this is meant to short circuit the UI and only trigger the one external IdP
            View = new ViewModel
            {
                EnableLocalLogin = local,
            };

            Input.Username = context?.LoginHint;

            if (!local)
            {
                View.ExternalProviders = new[] { new ViewModel.ExternalProvider {
                                                     AuthenticationScheme = context.IdP
                                                 } };
            }
        }

        var schemes = await _schemeProvider.GetAllSchemesAsync();

        var providers = schemes
                        .Where(x => x.DisplayName != null)
                        .Select(x => new ViewModel.ExternalProvider
        {
            DisplayName          = x.DisplayName ?? x.Name,
            AuthenticationScheme = x.Name
        }).ToList();

        var dyanmicSchemes = (await _identityProviderStore.GetAllSchemeNamesAsync())
                             .Where(x => x.Enabled)
                             .Select(x => new ViewModel.ExternalProvider
        {
            AuthenticationScheme = x.Scheme,
            DisplayName          = x.DisplayName
        });

        providers.AddRange(dyanmicSchemes);


        var allowLocal = true;

        if (context?.Client.ClientId != null)
        {
            var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

            if (client != null)
            {
                allowLocal = client.EnableLocalLogin;

                if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                {
                    providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                }
            }
        }

        View = new ViewModel
        {
            AllowRememberLogin = LoginOptions.AllowRememberLogin,
            EnableLocalLogin   = allowLocal && LoginOptions.AllowLocalLogin,
            ExternalProviders  = providers.ToArray()
        };
    }
Esempio n. 5
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app)
        {
            app.Run(async(context) =>
            {
                context.Response.ContentType = "text/plain";

                await context.Response.WriteAsync("Hello World - " + DateTimeOffset.Now + Environment.NewLine);
                await context.Response.WriteAsync(Environment.NewLine);

                await context.Response.WriteAsync("Address:" + Environment.NewLine);
                await context.Response.WriteAsync("Scheme: " + context.Request.Scheme + Environment.NewLine);
                await context.Response.WriteAsync("Host: " + context.Request.Headers["Host"] + Environment.NewLine);
                await context.Response.WriteAsync("PathBase: " + context.Request.PathBase.Value + Environment.NewLine);
                await context.Response.WriteAsync("Path: " + context.Request.Path.Value + Environment.NewLine);
                await context.Response.WriteAsync("Query: " + context.Request.QueryString.Value + Environment.NewLine);
                await context.Response.WriteAsync(Environment.NewLine);

                await context.Response.WriteAsync("Connection:" + Environment.NewLine);
                await context.Response.WriteAsync("RemoteIp: " + context.Connection.RemoteIpAddress + Environment.NewLine);
                await context.Response.WriteAsync("RemotePort: " + context.Connection.RemotePort + Environment.NewLine);
                await context.Response.WriteAsync("LocalIp: " + context.Connection.LocalIpAddress + Environment.NewLine);
                await context.Response.WriteAsync("LocalPort: " + context.Connection.LocalPort + Environment.NewLine);
                await context.Response.WriteAsync("ClientCert: " + context.Connection.ClientCertificate + Environment.NewLine);
                await context.Response.WriteAsync(Environment.NewLine);

                await context.Response.WriteAsync("User: "******"DisplayName: " + scheme?.DisplayName + Environment.NewLine);
                }

                await context.Response.WriteAsync(Environment.NewLine);

                await context.Response.WriteAsync("Headers:" + Environment.NewLine);
                foreach (var header in context.Request.Headers)
                {
                    await context.Response.WriteAsync(header.Key + ": " + header.Value + Environment.NewLine);
                }
                await context.Response.WriteAsync(Environment.NewLine);

                await context.Response.WriteAsync("Environment Variables:" + Environment.NewLine);
                var vars = Environment.GetEnvironmentVariables();
                foreach (var key in vars.Keys.Cast <string>().OrderBy(key => key, StringComparer.OrdinalIgnoreCase))
                {
                    var value = vars[key];
                    await context.Response.WriteAsync(key + ": " + value + Environment.NewLine);
                }
                await context.Response.WriteAsync(Environment.NewLine);

                // accessing IIS server variables
                await context.Response.WriteAsync("Server Variables:" + Environment.NewLine);

                foreach (var varName in IISServerVarNames)
                {
                    await context.Response.WriteAsync(varName + ": " + context.GetServerVariable(varName) + Environment.NewLine);
                }

                await context.Response.WriteAsync(Environment.NewLine);
                if (context.Features.Get <IHttpUpgradeFeature>() != null)
                {
                    await context.Response.WriteAsync("Websocket feature is enabled.");
                }
                else
                {
                    await context.Response.WriteAsync("Websocket feature is disabled.");
                }

                await context.Response.WriteAsync(Environment.NewLine);
                var addresses = context.RequestServices.GetService <IServer>().Features.Get <IServerAddressesFeature>();
                foreach (var key in addresses.Addresses)
                {
                    await context.Response.WriteAsync(key + Environment.NewLine);
                }
            });
        }
Esempio n. 6
0
        public async Task <ApiResponse> BuildLoginViewModel(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                var vm = new LoginViewModel
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    UserName         = context?.LoginHint
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } }
                }
                ;

                return(new ApiResponse(Status200OK, L["Operation Successful"], vm));
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null ||
                                   x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase)
                                   )
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.Client.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            return(new ApiResponse(Status200OK, L["Operation Successful"], new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                UserName = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            }));
        }
        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("/"));
        }
        public async Task <LoginViewModel> Handle(BuildLoginFlowBasedOnReturnUrl request, CancellationToken cancellationToken)
        {
            var returnUrl = request.ReturnUrl;

            // Take the authorization context from the return url
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            // Check if there is a try to connect using an identity provider like Google or Facebook
            // We should find this information from the request context and in the scheme provider of Identity Server
            // In order to bypass the login flow we should configure the idp in acr values (front channel of the request)
            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == IdentityServerConstants.LocalIdentityProvider;

                // Short cirquit the UI and trigger the external provider
                var vm = new LoginViewModel()
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } };
                }

                return(vm);
            }

            // Case when we create a classic login flow with html
            // Find all the authentication schemes
            var schemes = await _schemeProvider.GetAllSchemesAsync();

            // find the list with the external providers
            var providers = schemes.Where(x => x.DisplayName != null)
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            // Is the request from a authenticated client πχ like our mobile client
            if (context?.Client.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;
                }
            }

            return(new LoginViewModel
            {
                EnableLocalLogin = allowLocal,
                ReturnUrl = returnUrl,
                ExternalProviders = providers.ToArray()
            });
        }
        /*****************************************/
        /* helper APIs for the AccountController */
        /*****************************************/
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            AuthorizationRequest context = await interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null &&
                await schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                bool local = context.IdP == IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                LoginViewModel vm = new LoginViewModel
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    Username         = context?.LoginHint
                };

                if (!local)
                {
                    vm.ExternalProviders = new[]
                    {
                        new ExternalProvider
                        {
                            AuthenticationScheme = context.IdP
                        }
                    };
                }

                return(vm);
            }

            IEnumerable <AuthenticationScheme> schemes = await schemeProvider.GetAllSchemesAsync();

            List <ExternalProvider> providers = schemes
                                                .Where(x => x.DisplayName != null ||
                                                       x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName,
                                                                     StringComparison.OrdinalIgnoreCase))
                                                .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            })
                                                .ToList();

            bool allowLocal = true;

            if (context?.ClientId != null)
            {
                Client client = await clientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null &&
                        client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers
                                    .Where(provider =>
                                           client.IdentityProviderRestrictions.Contains(
                                               provider.AuthenticationScheme))
                                    .ToList();
                    }
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
        /*****************************************/
        /* helper APIs for the AccountController */
        /*****************************************/
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == Duende.IdentityServer.IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                var vm = new LoginViewModel
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    Username         = context?.LoginHint,
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } };
                }

                return(vm);
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null)
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.Client.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                    foreach (var provider in providers)
                    {
                        switch (provider.DisplayName)
                        {
                        case "Google":
                            provider.ImageUrl = "https://s.gr-assets.com/assets/gr/third_party/google_circle-694153be668f0720f058e755b6f136c6.png";
                            break;

                        //case "Facebook":
                        //    provider.ImageUrl = "https://s.gr-assets.com/assets/gr/share_module/share_facebook_circle-ecf94fc18c887e845025d979d27f758d.svg";
                        //    break;
                        //case "Twitter":
                        //    provider.ImageUrl = "https://s.gr-assets.com/assets/gr/share_module/share_twitter_circle-1e3cc199af6bf2bd798502acf873657a.svg";
                        //    break;
                        //case "Amazon":
                        //    provider.ImageUrl = "https://s.gr-assets.com/assets/gr/third_party/amazon_circle-5596868f0d928f2945f3374b01f5e10b.png";
                        //    break;
                        default:
                            break;
                        }
                    }
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
Esempio n. 11
0
        /*****************************************/
        /* helper APIs for the AccountController */
        /*****************************************/
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                var vm = new LoginViewModel
                {
                    EnableLocalLogin = local,
                    ReturnUrl        = returnUrl,
                    Username         = context?.LoginHint,
                };

                if (!local)
                {
                    vm.ExternalProviders = new[] { new ExternalProvider {
                                                       AuthenticationScheme = context.IdP
                                                   } };
                }

                return(vm);
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var LoginHintValues        = context?.LoginHint.Split('@');
            var domain                 = LoginHintValues?.Count() > 1 ? LoginHintValues[1] : null;
            var activeSchemesForDomain = (domain != null)? _tenantInfoRepository.Get(domain) : null;

            var providers = schemes
                            .Where(x => (x.DisplayName != null ||
                                         x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase)) && activeSchemesForDomain != null && activeSchemesForDomain.Schemes.Contains(x.Name)
                                   )
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            if (providers.Count == 1)
            {
                var vm = new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl        = returnUrl,
                    Username         = context?.LoginHint,
                };
                vm.ExternalProviders = new[] { new ExternalProvider {
                                                   AuthenticationScheme = providers[0].AuthenticationScheme
                                               } };
                return(vm);
            }
            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
        public async Task <Option <LoginOptions, string> > GetLoginOptions(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (_interactionConfig.Value.RequireAuthorizationRequest && context == null)
            {
                return(Option.None <LoginOptions, string>("A valid authorization request is required for login."));
            }

            // handle requests for specific identity provider
            if (context?.IdP != null && await _schemeProvider.GetSchemeAsync(context.IdP) != null)
            {
                var localLoginRequested = context.IdP == IdentityServerConstants.LocalIdentityProvider;

                // this is meant to short circuit the UI and only trigger the one external IdP
                return(new LoginOptions
                {
                    EnableLocalLogin = localLoginRequested,
                    LoginHint = context.LoginHint,
                    ExternalProviders = localLoginRequested
                        ? Enumerable.Empty <ExternalProvider>()
                        : new[] { new ExternalProvider {
                                      AuthenticationScheme = context.IdP
                                  } }
                }.Some <LoginOptions, string>());
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

            var providers = schemes
                            .Where(x => x.DisplayName != null)
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName ?? x.Name,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal = true;

            if (context?.Client.ClientId != null)
            {
                var client = await _clientStore.FindEnabledClientByIdAsync(context.Client.ClientId);

                if (client != null)
                {
                    allowLocal = client.EnableLocalLogin;

                    if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                    {
                        providers = providers.Where(provider => client.IdentityProviderRestrictions.Contains(provider.AuthenticationScheme)).ToList();
                    }
                }
            }

            return(new LoginOptions
            {
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                LoginHint = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            }.Some <LoginOptions, string>());
        }
Esempio n. 13
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);
            }
        }
Esempio n. 14
0
        private async Task <ModIdentityServerWebMvcPartAccountCommonJobLoginOutput> ProduceLogin(
            string returnUrl,
            ModIdentityServerBaseEnumLoginMethods loginMethod,
            IIdentityServerInteractionService interaction,
            IAuthenticationSchemeProvider schemeProvider,
            IClientStore clientStore
            )
        {
            var context = await interaction.GetAuthorizationContextAsync(returnUrl)
                          .CoreBaseExtTaskWithCurrentCulture(false);

            var result = new ModIdentityServerWebMvcPartAccountCommonJobLoginOutput(ResourceTitles, loginMethod)
            {
                ReturnUrl = returnUrl,
                Username  = context?.LoginHint
            };

            if (context?.IdP != null)
            {
                var scheme = await schemeProvider.GetSchemeAsync(context.IdP)
                             .CoreBaseExtTaskWithCurrentCulture(false);

                if (scheme != null)
                {
                    var local = context.IdP == IdentityServer4.IdentityServerConstants.LocalIdentityProvider;

                    // this is meant to short circuit the UI and only trigger the one external IdP
                    result.EnableLocalLogin = local;

                    if (!local)
                    {
                        result.ExternalProviders = new[]
                        {
                            new ModIdentityServerWebMvcPartAccountExternalProvider
                            {
                                AuthenticationScheme = context.IdP
                            }
                        };
                    }
                }
            }
            else
            {
                var schemes = await schemeProvider.GetAllSchemesAsync()
                              .CoreBaseExtTaskWithCurrentCulture(false);

                var providers = schemes.Where(x =>
                                              x.DisplayName != null
                                              ||
                                              x.Name.Equals(ConfigSettings.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase)
                                              ).Select(x =>
                                                       new ModIdentityServerWebMvcPartAccountExternalProvider
                {
                    DisplayName          = x.DisplayName,
                    AuthenticationScheme = x.Name
                }
                                                       ).ToList();

                var allowLocal = true;

                if (context?.ClientId != null)
                {
                    var client = await clientStore.FindEnabledClientByIdAsync(context.ClientId)
                                 .CoreBaseExtTaskWithCurrentCulture(false);

                    if (client != null)
                    {
                        allowLocal = client.EnableLocalLogin;

                        if (client.IdentityProviderRestrictions != null && client.IdentityProviderRestrictions.Any())
                        {
                            providers = providers.Where(
                                x => client.IdentityProviderRestrictions.Contains(x.AuthenticationScheme)
                                ).ToList();
                        }
                    }
                }

                result.AllowRememberLogin = ConfigSettings.AllowRememberLogin;
                result.EnableLocalLogin   = allowLocal && ConfigSettings.AllowLocalLogin;
                result.ExternalProviders  = providers.ToArray();
            }

            return(result);
        }
Esempio n. 15
0
        public async Task <Core.Models.AuthenticationScheme> GetSchemeAsync(string name)
        {
            var schema = await _schemeProvider.GetSchemeAsync(name);

            return(schema != null?_mapper.Map <AuthenticationScheme, Core.Models.AuthenticationScheme>(schema) : null);
        }
Esempio n. 16
0
        public async Task <IActionResult> PreValidate(string domainHint)
        {
            try
            {
                // Validate domain_hint provided
                if (string.IsNullOrWhiteSpace(domainHint))
                {
                    return(InvalidJson("NoOrganizationIdentifierProvidedError"));
                }

                // Validate organization exists from domain_hint
                var organization = await _organizationRepository.GetByIdentifierAsync(domainHint);

                if (organization == null)
                {
                    return(InvalidJson("OrganizationNotFoundByIdentifierError"));
                }
                if (!organization.UseSso)
                {
                    return(InvalidJson("SsoNotAllowedForOrganizationError"));
                }

                // Validate SsoConfig exists and is Enabled
                var ssoConfig = await _ssoConfigRepository.GetByIdentifierAsync(domainHint);

                if (ssoConfig == null)
                {
                    return(InvalidJson("SsoConfigurationNotFoundForOrganizationError"));
                }
                if (!ssoConfig.Enabled)
                {
                    return(InvalidJson("SsoNotEnabledForOrganizationError"));
                }

                // Validate Authentication Scheme exists and is loaded (cache)
                var scheme = await _schemeProvider.GetSchemeAsync(organization.Id.ToString());

                if (scheme == null || !(scheme is IDynamicAuthenticationScheme dynamicScheme))
                {
                    return(InvalidJson("NoSchemeOrHandlerForSsoConfigurationFoundError"));
                }

                // Run scheme validation
                try
                {
                    await dynamicScheme.Validate();
                }
                catch (Exception ex)
                {
                    var translatedException = _i18nService.GetLocalizedHtmlString(ex.Message);
                    var errorKey            = "InvalidSchemeConfigurationError";
                    if (!translatedException.ResourceNotFound)
                    {
                        errorKey = ex.Message;
                    }
                    return(InvalidJson(errorKey, translatedException.ResourceNotFound ? ex : null));
                }

                var tokenable = new SsoTokenable(organization, _globalSettings.Sso.SsoTokenLifetimeInSeconds);
                var token     = _dataProtector.Protect(tokenable);

                return(new SsoPreValidateResponseModel(token));
            }
            catch (Exception ex)
            {
                return(InvalidJson("PreValidationError", ex));
            }
        }