예제 #1
0
        public AccountController_Tests()
        {
            var mockOptionsAccessor    = Substitute.For <IOptions <IdentityOptions> >();
            var mockPasswordHasher     = Substitute.For <IPasswordHasher <UserModel> >();
            var mockUserValidators     = Substitute.For <IEnumerable <IUserValidator <UserModel> > >();
            var mockPasswordValidators = Substitute.For <IEnumerable <IPasswordValidator <UserModel> > >();
            var mockKeyNormalizer      = Substitute.For <ILookupNormalizer>();
            var mockErrors             = Substitute.For <IdentityErrorDescriber>();
            var mockServices           = Substitute.For <IServiceProvider>();
            var mockUserLogger         = Substitute.For <ILogger <UserManager <UserModel> > >();
            var fakeA3SContext         = new A3SContextFake(new Microsoft.EntityFrameworkCore.DbContextOptions <A3SContext>());

            mockConfiguration = Substitute.For <IConfiguration>();
            var fakesCustomUserStore = new CustomUserStoreFake(fakeA3SContext, mockConfiguration);

            fakeUserManager = new CustomUserManagerFake(fakesCustomUserStore, mockOptionsAccessor, mockPasswordHasher, mockUserValidators, mockPasswordValidators, mockKeyNormalizer,
                                                        mockErrors, mockServices, mockUserLogger);

            var mockContextAccessor = Substitute.For <IHttpContextAccessor>();
            var mocClaimsFactory    = Substitute.For <IUserClaimsPrincipalFactory <UserModel> >();
            var mockSignInLogger    = Substitute.For <ILogger <SignInManager <UserModel> > >();
            var mockLdapAuthenticationModeRepository = Substitute.For <LdapAuthenticationModeRepository>(fakeA3SContext, mockConfiguration);
            var mockLdapConnectionService            = Substitute.For <ILdapConnectionService>();

            mockAuthenticationSchemeProvider = Substitute.For <IAuthenticationSchemeProvider>();
            var mockUserConfirmation = Substitute.For <IUserConfirmation <UserModel> >();

            fakeSignInManager = new CustomSignInManagerFake <UserModel>(fakeUserManager, mockContextAccessor, mocClaimsFactory, mockOptionsAccessor, mockSignInLogger, fakeA3SContext,
                                                                        mockAuthenticationSchemeProvider, mockLdapAuthenticationModeRepository, mockLdapConnectionService, mockUserConfirmation);

            mockIdentityServerInteractionService = Substitute.For <IIdentityServerInteractionService>();
            mockClientStore  = Substitute.For <IClientStore>();
            mockEventService = Substitute.For <IEventService>();
            urlTestEncoder   = new UrlTestEncoder();

            // Prepare controller contexts
            authorizationRequest = new AuthorizationRequest()
            {
                IdP       = "testIdp",
                ClientId  = "clientId1",
                LoginHint = "LoginHint"
            };

            var mockAuthenticationHandler = Substitute.For <IAuthenticationHandler>();

            mockAuthenticationSchemeProvider.GetAllSchemesAsync()
            .Returns(new List <AuthenticationScheme>()
            {
                new AuthenticationScheme("testName", AccountOptions.WindowsAuthenticationSchemeName, mockAuthenticationHandler.GetType())
            });

            client = new Client()
            {
                EnableLocalLogin = true
            };

            client.IdentityProviderRestrictions.Add(AccountOptions.WindowsAuthenticationSchemeName);
            mockClientStore.FindEnabledClientByIdAsync(Arg.Any <string>()).Returns(client);

            userModel = new UserModel()
            {
                UserName = "******",
                Id       = Guid.NewGuid().ToString()
            };
        }
        public Task Invoke(
            HttpContext context,
            TenantDbContext _db,
            IOptionsMonitor <IdentityServerAuthenticationOptions> identityServerAuthenticationOptions)
        {
            var tenant = _tenantService.GetTenant(_db,
                                                  context.Request.Host.Value);

            if (tenant.Item1 != null)
            {
                context.Items[TenantConstant.CacheKey] = tenant.Item1;
            }

            var ResetOAuthProvider_CacheKey = TenantConstant.SchemesReflush + context.Request.Host.Value;

            var ResetOAuthProvider_Flag = _memoryCache.Get <string>(ResetOAuthProvider_CacheKey);

            if (tenant.Item2 != null)
            {
                var pvtModel = tenant.Item2;

                #region IdentityServer4 - IssuerUri
                _identityServerOptions.IssuerUri = context.Request.Scheme + "://" + tenant.Item2.IdentityServerIssuerUri;
                #endregion

                #region IdentityServer4 - AuthorityUri
                identityServerAuthenticationOptions.CurrentValue.Authority = _identityServerOptions.IssuerUri;
                #endregion

                #region ResetOAuthProvider - PerRequest
                if (string.IsNullOrWhiteSpace(ResetOAuthProvider_Flag) && pvtModel.Properties.Count > 0)
                {
                    // All Schemes
                    var ApplicationSchemes = _oauthProvider.GetAllSchemesAsync().Result.Select(x => x.Name).ToList();

                    // All Scheme Providers
                    var SchemeProviders = OAuthBuilderExtensions.Handlers.Select(x => x.Key).ToList();

                    foreach (var oauthScheme in SchemeProviders)
                    {
                        var ClientId_FromTenant = pvtModel.Properties[$"{oauthScheme}:ClientId"];

                        var ClientSecret_FromTenant = pvtModel.Properties[$"{oauthScheme}:ClientSecret"];

                        if (string.IsNullOrWhiteSpace(ClientId_FromTenant) ||
                            string.IsNullOrWhiteSpace(ClientSecret_FromTenant))
                        {
                            _oauthProvider.RemoveScheme(oauthScheme);

                            continue;
                        }

                        switch (oauthScheme)
                        {
                        case AmazonAuthenticationDefaults.AuthenticationScheme:
                            _amazonOptions.ClientId     = ClientId_FromTenant;
                            _amazonOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case FacebookDefaults.AuthenticationScheme:
                            _facebookOptions.ClientId     = ClientId_FromTenant;
                            _facebookOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case GitHubDefaults.AuthenticationScheme:
                            _amazonOptions.ClientId     = ClientId_FromTenant;
                            _amazonOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case GitterAuthenticationDefaults.AuthenticationScheme:
                            _gitterOptions.ClientId     = ClientId_FromTenant;
                            _gitterOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case GoogleDefaults.AuthenticationScheme:
                            _googleOptions.ClientId     = ClientId_FromTenant;
                            _googleOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case InstagramAuthenticationDefaults.AuthenticationScheme:
                            _instagramOptions.ClientId     = ClientId_FromTenant;
                            _instagramOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case LinkedInAuthenticationDefaults.AuthenticationScheme:
                            _linkedinOptions.ClientId     = ClientId_FromTenant;
                            _linkedinOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case MicrosoftAccountDefaults.AuthenticationScheme:
                            _microsoftOptions.ClientId     = ClientId_FromTenant;
                            _microsoftOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case PaypalAuthenticationDefaults.AuthenticationScheme:
                            _paypalOptions.ClientId     = ClientId_FromTenant;
                            _paypalOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case QQDefaults.AuthenticationScheme:
                            _amazonOptions.ClientId     = ClientId_FromTenant;
                            _amazonOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case RedditAuthenticationDefaults.AuthenticationScheme:
                            _redditOptions.ClientId     = ClientId_FromTenant;
                            _redditOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case SalesforceAuthenticationDefaults.AuthenticationScheme:
                            _salesforceOptions.ClientId     = ClientId_FromTenant;
                            _salesforceOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case TwitterDefaults.AuthenticationScheme:
                            _twitterOptions.ConsumerKey    = ClientId_FromTenant;
                            _twitterOptions.ConsumerSecret = ClientSecret_FromTenant;
                            break;

                        case VisualStudioAuthenticationDefaults.AuthenticationScheme:
                            _visualstudioOptions.ClientId     = ClientId_FromTenant;
                            _visualstudioOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case WeiboDefaults.AuthenticationScheme:
                            _weiboOptions.ClientId     = ClientId_FromTenant;
                            _weiboOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case WeixinDefaults.AuthenticationScheme:
                            _weixinOptions.ClientId     = ClientId_FromTenant;
                            _weixinOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        case WordPressAuthenticationDefaults.AuthenticationScheme:
                            _wordpressOptions.ClientId     = ClientId_FromTenant;
                            _wordpressOptions.ClientSecret = ClientSecret_FromTenant;
                            break;

                        default: break;
                        }

                        if (!ApplicationSchemes.Contains(oauthScheme))
                        {
                            _oauthProvider.AddScheme(new AuthenticationScheme(oauthScheme,
                                                                              oauthScheme, OAuthBuilderExtensions.Handlers[oauthScheme]));
                        }
                    }

                    _memoryCache.Set(ResetOAuthProvider_CacheKey,
                                     "1",
                                     TimeSpan.FromSeconds(TenantConstant.SchemesReflushDuration));
                }
                #endregion
            }

            return(_next(context));
        }
 public IActionResult GetAllSchemes()
 {
     return(Ok(provider.GetAllSchemesAsync().Result));
 }
        /// <summary>
        /// 生成登录试图模型
        /// </summary>
        /// <param name="returnUrl">跳转回的客户端uri</param>
        /// <returns>LoginViewModel</returns>
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            //获取AuthorizationURI中得参数保存至AuthorizationRequest实体上
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            //如果AuthorizationRequest包好IDP信息,则为外部IDP,如果没有,则为本地IDP
            if (context?.IdP != null)
            {
                // this is meant to short circuit the UI and only trigger the one external IdP
                // 触发一个外部IdP
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = new ExternalProvider[] { new ExternalProvider {
                                                                     AuthenticationScheme = context.IdP
                                                                 } }
                });
            }
            //获取所有认证方案
            var schemes = await _schemeProvider.GetAllSchemesAsync();

            //获取所有外部idp
            var providers = schemes
                            .Where(x => x.DisplayName != null ||
                                   (x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
                                   )
                            .Select(x => new ExternalProvider
            {
                DisplayName          = x.DisplayName,
                AuthenticationScheme = x.Name
            }).ToList();

            //允许本地认证
            var allowLocal = true;

            if (context?.ClientId != null)
            {
                //通过Request的ClientId从IDP中检索目前启用状态的Client配置,并返回Client实例
                var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId);

                if (client != null)
                {
                    //获取该客户端是否允许本地登录
                    allowLocal = client.EnableLocalLogin;

                    //判断,是否配置了可以与客户端一起使用的外部Idp,如果为IdentityProviderRestrictions为空,则允许所有idp,该值默认为null
                    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()
            });
        }
예제 #5
0
        public async Task <IEnumerable <Core.Models.AuthenticationScheme> > GetAllSchemesAsync()
        {
            var schemes = await _schemeProvider.GetAllSchemesAsync();

            return(_mapper.Map <IEnumerable <AuthenticationScheme>, IEnumerable <Core.Models.AuthenticationScheme> >(schemes));
        }
예제 #6
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()
        };
    }
예제 #7
0
        async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null)
            {
                // this is meant to short circuit the UI and only trigger the one external IdP
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = new ExternalProvider[] { new ExternalProvider {
                                                                     AuthenticationScheme = context.IdP
                                                                 } }
                });
            }

            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,
                AuthenticationScheme = x.Name
            }).ToList();

            var allowLocal  = true;
            var logoUrl     = string.Empty;
            var companyName = string.Empty;

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

                var company = _context.Company.AsQueryable().SingleOrDefault(s => s.Id == context.ClientId);
                if (company != null)
                {
                    logoUrl     = company.LogoUrl;
                    companyName = company.CompanyName;
                }
            }

            return(new LoginViewModel
            {
                RememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray(),
                LogoUrl = logoUrl,
                CompanyName = companyName
            });
        }
예제 #8
0
        public async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null)
            {
                // this is meant to short circuit the UI and only trigger the one external IdP
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = new ExternalProvider[] { new ExternalProvider {
                                                                     AuthenticationScheme = context.IdP
                                                                 } }
                });
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync();

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

            if (AccountOptions.WindowsAuthenticationEnabled)
            {
                // this is needed to handle windows auth schemes
                var windowsSchemes = schemes.Where(s => s.Name == AccountOptions.WindowsAuthenticationSchemeName);
                if (windowsSchemes.Any())
                {
                    providers.Add(new ExternalProvider
                    {
                        AuthenticationScheme = AccountOptions.WindowsAuthenticationSchemeName,
                        DisplayName          = AccountOptions.WindowsAuthenticationSchemeName
                    });
                }
            }

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

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
예제 #9
0
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interactionService.GetAuthorizationContextAsync(returnUrl).ConfigureAwait(false);

            if (context?.IdP != null)
            {
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = new[] { new ExternalProvider {
                                                    AuthenticationScheme = context.IdP
                                                } }
                });
            }

            var schemes = await _schemeProvider.GetAllSchemesAsync().ConfigureAwait(false);

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

            var allowLocal = true;

            if (context?.ClientId == null)
            {
                return(new LoginViewModel
                {
                    AllowRememberLogin = AccountOptions.AllowRememberLogin,
                    EnableLocalLogin = AccountOptions.AllowLocalLogin,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = providers.ToArray()
                });
            }

            var client = await _clientStore.FindEnabledClientByIdAsync(context.ClientId).ConfigureAwait(false);

            if (client == null)
            {
                return(new LoginViewModel
                {
                    AllowRememberLogin = AccountOptions.AllowRememberLogin,
                    EnableLocalLogin = AccountOptions.AllowLocalLogin,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = providers.ToArray()
                });
            }

            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)
            {
                var local = context.IdP == 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,
                    ShowDefaultUserPass = _configuration["ApplicationSettings:ShowDefaultUserPass"] == "true"
                };

                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 ||
                                   (x.Name.Equals(AccountOptions.WindowsAuthenticationSchemeName, StringComparison.OrdinalIgnoreCase))
                                   )
                            .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();
                    }
                }
            }

            return(new LoginViewModel
            {
                EnableExternalProviders = providers.Any() && _configuration.GetValue <bool>("ApplicationSettings:EnableExternalProviders"),
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray(),
                ShowDefaultUserPass = _configuration["ApplicationSettings:ShowDefaultUserPass"] == "true"
            });
        }
예제 #11
0
        /*****************************************/
        /* helper APIs for the AccountController */
        /*****************************************/
        private async Task <LoginViewModel> BuildLoginViewModelAsync(
            string returnUrl, ICookieHandler cookieHandler)
        {
            var rememberLogin = cookieHandler != null
        ? cookieHandler.GetBoolValue(Cookies.cookieKeyRememberLogin)
        : false;

            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null)
            {
                // this is meant to short circuit the UI and only trigger the one external IdP
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    ExternalProviders = new ExternalProvider[] { new ExternalProvider {
                                                                     AuthenticationScheme = context.IdP
                                                                 } }
                });
            }

            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,
                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();
                    }
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                RememberLogin = rememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                ExternalProviders = providers.ToArray()
            });
        }
예제 #12
0
        /*****************************************/
        /* 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()
            });
        }
예제 #13
0
        public async Task <IActionResult> Login()
        {
            LoginViewModel loginViewModel = new LoginViewModel();

            loginViewModel.AllSchemeProvider = (await authenticationSchemeProvider.GetAllSchemesAsync())
                                               .Select(n => n.DisplayName).Where(n => !String.IsNullOrEmpty(n));

            if (User.Identity.IsAuthenticated == true)
            {
                using (var unitOfWork = new UnitOfWork(new CuriousDriveContext()))
                {
                    //Login
                    CuriousDriveWebAPI.CuriousDrive.Models.User user = unitOfWork.Users.GetSocialNetworkUserByEmailAddress(User.Claims.Where(claim => claim.Type == ClaimTypes.Email).FirstOrDefault().Value);

                    if (user != null)
                    {
                        LoadSession(user);
                        return(RedirectToAction("Questions", "Question"));
                    }
                    else
                    {
                        //Register and then login
                        user = new User();
                        string saltValue = Security.GetSaltValue();
                        MD5    md5Hash   = MD5.Create();

                        user.EmailAddress        = User.Claims.Where(claim => claim.Type == ClaimTypes.Email).FirstOrDefault().Value;
                        user.FirstName           = User.Claims.Where(claim => claim.Type == ClaimTypes.GivenName).FirstOrDefault().Value;
                        user.LastName            = User.Claims.Where(claim => claim.Type == ClaimTypes.Surname).FirstOrDefault().Value;
                        user.DisplayName         = User.Claims.Where(claim => claim.Type == ClaimTypes.Name).FirstOrDefault().Value;
                        user.Password            = Security.GetMd5Hash(md5Hash, saltValue + user.EmailAddress);
                        user.SaltValue           = Security.Encrypt(saltValue);
                        user.IsUserVerified      = Constant.FlagY;
                        user.IsPasswordForgotten = Constant.FlagN;
                        user.UserStatusId        = Constant.UserStatusId;
                        user.UserStatusValue     = Constant.Active;
                        user.NetworkId           = Constant.NetworkId;

                        if (User.Identity.AuthenticationType == "Facebook")
                        {
                            user.NetworkValue = Constant.FacebookNetwork;
                        }
                        if (User.Identity.AuthenticationType == "Google")
                        {
                            user.NetworkValue = Constant.GoogleNetwork;
                        }

                        user.CreatedBy = user.ModifiedBy = 1;

                        user.UserRole = new Collection <CuriousDriveWebAPI.CuriousDrive.Models.UserRole>();
                        UserRole userRole = new UserRole();

                        userRole.RoleId    = unitOfWork.Roles.Find(role => role.RoleName == Constant.RoleStudent).FirstOrDefault().RoleId;
                        userRole.CreatedBy = user.ModifiedBy = 1;

                        user.UserRole.Add(userRole);
                        unitOfWork.Users.Add(user);

                        unitOfWork.Complete();

                        LoadSession(user);
                        return(RedirectToAction("Questions", "Question"));
                    }
                }
            }

            return(View(loginViewModel));
        }
예제 #14
0
 public async Task <IEnumerable <AuthenticationScheme> > GetExternalAuthenticationSchemesAsync()
 {
     return((await _schemes.GetAllSchemesAsync()).Where(s => !string.IsNullOrEmpty(s.DisplayName)));
 }
예제 #15
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);
        }
예제 #16
0
        public async Task <IActionResult> Challenge(string scheme, string returnUrl)
        {
            if (!interaction.IsValidReturnUrl(returnUrl) || string.IsNullOrWhiteSpace(scheme) || !(await schemeProvider.GetAllSchemesAsync()).Any(s => s.Name == scheme))
            {
                return(Redirect("/"));
            }

            return(Challenge(new AuthenticationProperties
            {
                RedirectUri = Url.Action(nameof(Callback)),
                Items =
                {
                    { "returnUrl", returnUrl }
                }
            }, scheme));
        }
예제 #17
0
        private async Task <SignInViewModel> CreateSigninModelAsync(string returnUrl)
        {
            var context = await interactions.GetAuthorizationContextAsync(returnUrl);

            if (null != context?.IdP)
            {
                return(new SignInViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Email = context.LoginHint,
                    ExternalProviders =
                    {
                        new ExternalProvider
                        {
                            AuthenticationScheme = context.IdP
                        }
                    }
                });
            }

            var schemes = await schemeProvider.GetAllSchemesAsync();

            var comparer  = StringComparer.OrdinalIgnoreCase;
            var condition = new Func <AuthenticationScheme, bool>(scheme =>
                                                                  null != scheme.DisplayName || comparer.Equals(scheme.Name, AccountOptions.WindowsAuthenticationScheme)
                                                                  );
            var canSigninLocal = true;
            var providers      = schemes
                                 .Where(condition)
                                 .Select(scheme => new ExternalProvider
            {
                DisplayName          = scheme.DisplayName,
                AuthenticationScheme = scheme.Name
            })
                                 .ToArray();

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

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

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

            captcha.Create(HttpContext);

            return(new SignInViewModel
            {
                AllowRememberMe = AccountOptions.AllowRememberMe,
                EnableLocalLogin = canSigninLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Email = context?.LoginHint,
                ExternalProviders = providers
            });
        }
예제 #18
0
 public DefaultRequestIsAuthenticate(IAuthenticationSchemeProvider authenticationService)
 {
     _authenticationSchemes = authenticationService.GetAllSchemesAsync().GetAwaiter().GetResult().ToList();
 }
예제 #19
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()
            });
        }
예제 #20
0
        private async Task <LoginViewModel> BuildLoginViewModelAsync(string returnUrl)
        {
            var context = await _interaction.GetAuthorizationContextAsync(returnUrl);

            if (context?.IdP != null)
            {
                // this is meant to short circuit the UI and only trigger the one external IdP
                return(new LoginViewModel
                {
                    EnableLocalLogin = false,
                    ReturnUrl = returnUrl,
                    Username = context?.LoginHint,
                    LoginResolutionPolicy = _loginConfiguration.ResolutionPolicy,
                    ExternalProviders = new ExternalProvider[] { new ExternalProvider {
                                                                     AuthenticationScheme = context.IdP
                                                                 } }
                });
            }

            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,
                AuthenticationScheme = x.Name
            }).ToList();

            var    allowLocal      = true;
            string customLoginPage = null;

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



                    //hongsh: 支持自定义登录页
                    customLoginPage = client.Properties.FirstOrDefault(s => s.Key.ToLower() == "login").Value;
                    //_logger.LogDebug($"Find custom login page:\r\n[loginPage]:{loginPage}");
                }
            }

            return(new LoginViewModel
            {
                AllowRememberLogin = AccountOptions.AllowRememberLogin,
                EnableLocalLogin = allowLocal && AccountOptions.AllowLocalLogin,
                ReturnUrl = returnUrl,
                Username = context?.LoginHint,
                LoginResolutionPolicy = _loginConfiguration.ResolutionPolicy,
                ExternalProviders = providers.ToArray(),
                CustomLoginPage = customLoginPage
            });
        }