Esempio n. 1
0
        private void RemoveScheme(AuthenticationScheme scheme)
        {
            schemeProvider.RemoveScheme(scheme.Name);
            optionsCache.TryRemove(scheme.Name);

            logger.LogInformation("Removed external authentication {ExternalLogin} for tenant {Tenant}.", scheme.Name, resolvedTenant.TenantName);
        }
Esempio n. 2
0
        public async Task InvokeAsync(HttpContext context,
                                      IAuthenticationSchemeProvider schemeProvider,
                                      IOptionsMonitorCache <FakeAuthenticationSchemeOptions> optionsCache)
        {
            var fakeOptions = context.RequestServices
                              .GetRequiredService <IOptionsSnapshot <FakeAuthenticationOptions> >().Value;

            foreach (var fakeScheme in fakeOptions.Schemes)
            {
                if (await schemeProvider.GetSchemeAsync(fakeScheme.SchemeName) != null)
                {
                    schemeProvider.RemoveScheme(fakeScheme.SchemeName);
                    optionsCache.TryRemove(fakeScheme.SchemeName);
                    var scheme = new AuthenticationScheme(fakeScheme.SchemeName,
                                                          fakeScheme.SchemeName,
                                                          typeof(FakeAuthenticationHandler));
                    schemeProvider.AddScheme(scheme);
                    var fakeSchemeOptions = new FakeAuthenticationSchemeOptions();
                    foreach (var claim in fakeScheme.Claims)
                    {
                        fakeSchemeOptions.Claims.Add(claim);
                    }
                    optionsCache.TryAdd(fakeScheme.SchemeName, fakeSchemeOptions);
                }
            }
            await _next(context);
        }
Esempio n. 3
0
        /// <summary>
        /// Adds a scheme asynchronously.
        /// </summary>
        /// <param name="definition">The definition.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">definition</exception>
        public virtual async Task AddAsync(ISchemeDefinition definition, CancellationToken cancellationToken = default)
        {
            definition = definition ?? throw new ArgumentNullException(nameof(definition));

            var handlerType         = definition.HandlerType;
            var optionsType         = GetOptionsType(handlerType);
            var optionsMonitorCache = _wrapperFactory.Get(optionsType);

            var scheme = definition.Scheme;

            if (await _schemeProvider.GetSchemeAsync(scheme).ConfigureAwait(false) != null)
            {
                _schemeProvider.RemoveScheme(scheme);
                optionsMonitorCache.TryRemove(scheme);
            }

            _schemeProvider.AddScheme(new AuthenticationScheme(scheme, definition.DisplayName, handlerType));
            optionsMonitorCache.TryAdd(scheme, definition.Options);
        }
        /// <inheritdoc />
        public async Task ConfigureAsync()
        {
            // Remove all schemes
            var allSchemes = await _schemeProvider.GetAllSchemesAsync();

            var filteredSchemes = allSchemes.Where(x => !ExcludedSchemes.Contains(x.Name));

            foreach (var authenticationScheme in filteredSchemes)
            {
                _schemeProvider.RemoveScheme(authenticationScheme.Name);
            }

            // Add schemes based on identity providers
            var identityProviders = await _sgIdentityProviderStore.GetAllAsync();

            foreach (var identityProvider in identityProviders)
            {
                if (!identityProvider.IsEnabled)
                {
                    continue;
                }

                AuthenticationScheme scheme;
                switch (identityProvider)
                {
                case GoogleIdentityProvider googleIdentityProvider:
                    scheme = _authSchemeCreatorFactory.GetCreator <GoogleIdentityProvider>()
                             .Create(googleIdentityProvider);
                    break;

                case MicrosoftIdentityProvider microsoftIdentityProvider:
                    scheme = _authSchemeCreatorFactory.GetCreator <MicrosoftIdentityProvider>()
                             .Create(microsoftIdentityProvider);
                    break;

                case AzureAdIdentityProvider azureAdIdentityProvider:
                    scheme = _authSchemeCreatorFactory.GetCreator <AzureAdIdentityProvider>()
                             .Create(azureAdIdentityProvider);
                    break;

                default:
                    throw new NotImplementedException(
                              $"Identity provider '{identityProvider.Type}' is not supported.");
                }

                _schemeProvider.AddScheme(scheme);
            }
        }
Esempio n. 5
0
 public void RemoveScheme(string name)
 {
     _inner.RemoveScheme(name);
 }
Esempio n. 6
0
        public Task Invoke(
            HttpContext context)
        {
            var _tenantService = context.RequestServices.GetService <TenantService>();

            var tenant = _tenantService.GetTenant(context.Request.Host.Value);

            if (tenant.Item1 == null || tenant.Item2 == null)
            {
                context.Response.StatusCode = 400;

                return(context.Response.WriteAsync("error page"));
            }

            context.Items[TenantConstant.CacheKey] = tenant.Item1;

            context.Items[TenantConstant.HttpContextItemKey] = tenant.Item2;

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

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

            var TenantProperties = tenant.Item2.Properties;

            var IssuerUri = $"{context.Request.Scheme}://{tenant.Item2.IdentityServerIssuerUri}";

            #region IdentityServer4 - IssuerUri
            _identityServerOptions.IssuerUri = IssuerUri;
            #endregion

            #region ResetUserInteraction
            if (TenantProperties.ContainsKey(UserInteractionKeys.Enable) &&
                TenantProperties[UserInteractionKeys.Enable].Equals("true"))
            {
                if (TenantProperties.ContainsKey(UserInteractionKeys.LoginUrl))
                {
                    _identityServerOptions.UserInteraction.LoginUrl = TenantProperties[UserInteractionKeys.LoginUrl];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.LoginReturnUrlParameter))
                {
                    _identityServerOptions.UserInteraction.LoginReturnUrlParameter = TenantProperties[UserInteractionKeys.LoginReturnUrlParameter];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.LogoutUrl))
                {
                    _identityServerOptions.UserInteraction.LogoutUrl = TenantProperties[UserInteractionKeys.LogoutUrl];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.LogoutIdParameter))
                {
                    _identityServerOptions.UserInteraction.LogoutIdParameter = TenantProperties[UserInteractionKeys.LogoutIdParameter];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.ConsentUrl))
                {
                    _identityServerOptions.UserInteraction.ConsentUrl = TenantProperties[UserInteractionKeys.ConsentUrl];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.ConsentReturnUrlParameter))
                {
                    _identityServerOptions.UserInteraction.ConsentReturnUrlParameter = TenantProperties[UserInteractionKeys.ConsentReturnUrlParameter];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.ErrorUrl))
                {
                    _identityServerOptions.UserInteraction.ErrorUrl = TenantProperties[UserInteractionKeys.ErrorUrl];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.ErrorIdParameter))
                {
                    _identityServerOptions.UserInteraction.ErrorIdParameter = TenantProperties[UserInteractionKeys.ErrorIdParameter];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.CustomRedirectReturnUrlParameter))
                {
                    _identityServerOptions.UserInteraction.CustomRedirectReturnUrlParameter = TenantProperties[UserInteractionKeys.CustomRedirectReturnUrlParameter];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.CookieMessageThreshold))
                {
                    if (int.TryParse(TenantProperties[UserInteractionKeys.CookieMessageThreshold], out int _i))
                    {
                        _identityServerOptions.UserInteraction.CookieMessageThreshold = _i;
                    }
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.DeviceVerificationUrl))
                {
                    _identityServerOptions.UserInteraction.DeviceVerificationUrl = TenantProperties[UserInteractionKeys.DeviceVerificationUrl];
                }
                if (TenantProperties.ContainsKey(UserInteractionKeys.DeviceVerificationUserCodeParameter))
                {
                    _identityServerOptions.UserInteraction.DeviceVerificationUserCodeParameter = TenantProperties[UserInteractionKeys.DeviceVerificationUserCodeParameter];
                }
            }
            #endregion

            #region ResetOAuthProvider - PerRequest
            if (string.IsNullOrWhiteSpace(ResetOAuthProvider_Flag) && TenantProperties.Count > 0)
            {
                var AppSchemes = _oauthProvider.GetAllSchemesAsync().Result.Select(x => x.Name).ToList();

                foreach (var scheme in OAuthBuilderExtensions.Schemes)
                {
                    if (!TenantProperties.ContainsKey($"{scheme}:ClientId") ||
                        !TenantProperties.ContainsKey($"{scheme}:ClientSecret"))
                    {
                        _oauthProvider.RemoveScheme(scheme);
                        continue;
                    }

                    var ClientId_FromTenant     = TenantProperties[$"{scheme}:ClientId"];
                    var ClientSecret_FromTenant = TenantProperties[$"{scheme}:ClientSecret"];

                    if (string.IsNullOrWhiteSpace(ClientId_FromTenant) ||
                        string.IsNullOrWhiteSpace(ClientSecret_FromTenant))
                    {
                        _oauthProvider.RemoveScheme(scheme);
                        continue;
                    }

                    switch (scheme)
                    {
                    case MicrosoftAccountDefaults.AuthenticationScheme:
                        _microsoftOptions.ClientId     = ClientId_FromTenant;
                        _microsoftOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(MicrosoftAccountHandler));
                        break;

                    case GoogleDefaults.AuthenticationScheme:
                        _googleOptions.ClientId     = ClientId_FromTenant;
                        _googleOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(GoogleHandler));
                        break;

                    case WeiboAuthenticationDefaults.AuthenticationScheme:
                        _weiboOptions.ClientId     = ClientId_FromTenant;
                        _weiboOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(WeiboAuthenticationHandler));
                        break;

                    case WeixinAuthenticationDefaults.AuthenticationScheme:
                        _weixinOptions.ClientId     = ClientId_FromTenant;
                        _weixinOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(WeixinAuthenticationHandler));
                        break;

                    case QQAuthenticationDefaults.AuthenticationScheme:
                        _qqOptions.ClientId     = ClientId_FromTenant;
                        _qqOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(QQAuthenticationHandler));
                        break;

                    case GitHubAuthenticationDefaults.AuthenticationScheme:
                        _githubOptions.ClientId     = ClientId_FromTenant;
                        _githubOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(GitHubAuthenticationHandler));
                        break;

                    case FacebookDefaults.AuthenticationScheme:
                        _facebookOptions.ClientId     = ClientId_FromTenant;
                        _facebookOptions.ClientSecret = ClientSecret_FromTenant;
                        AddSchemeIfNotExists(AppSchemes, scheme, typeof(FacebookHandler));
                        break;

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

                    //case GitterAuthenticationDefaults.AuthenticationScheme:
                    //    _gitterOptions.ClientId = ClientId_FromTenant;
                    //    _gitterOptions.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 PaypalAuthenticationDefaults.AuthenticationScheme:
                    //    _paypalOptions.ClientId = ClientId_FromTenant;
                    //    _paypalOptions.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 WordPressAuthenticationDefaults.AuthenticationScheme:
                    //    _wordpressOptions.ClientId = ClientId_FromTenant;
                    //    _wordpressOptions.ClientSecret = ClientSecret_FromTenant;
                    //    break;

                    default: break;
                    }
                }

                var MemoryCacheOptions = new MemoryCacheEntryOptions();

                MemoryCacheOptions.SetAbsoluteExpiration(
                    TimeSpan.FromSeconds(TenantConstant.SchemesReflushDuration));

                _memoryCache.Set(ResetOAuthProvider_CacheKey,
                                 "1",
                                 MemoryCacheOptions);
            }
            #endregion

            return(_next.Invoke(context));
        }
Esempio n. 7
0
 public IActionResult Remove(string scheme)
 {
     _schemeProvider.RemoveScheme(scheme);
     _optionsCache.TryRemove(scheme);
     return(Redirect("/"));
 }
Esempio n. 8
0
        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)
                {
                    var AppSchemes = _oauthProvider.GetAllSchemesAsync().Result.Select(x => x.Name).ToList();

                    foreach (var scheme in OAuthBuilderExtensions.Schemes)
                    {
                        if (!pvtModel.Properties.ContainsKey($"{scheme}:ClientId") ||
                            !pvtModel.Properties.ContainsKey($"{scheme}:ClientSecret"))
                        {
                            _oauthProvider.RemoveScheme(scheme);
                            continue;
                        }

                        var ClientId_FromTenant     = pvtModel.Properties[$"{scheme}:ClientId"];
                        var ClientSecret_FromTenant = pvtModel.Properties[$"{scheme}:ClientSecret"];

                        if (string.IsNullOrWhiteSpace(ClientId_FromTenant) ||
                            string.IsNullOrWhiteSpace(ClientSecret_FromTenant))
                        {
                            _oauthProvider.RemoveScheme(scheme);
                            continue;
                        }

                        switch (scheme)
                        {
                        case MicrosoftAccountDefaults.AuthenticationScheme:
                            _microsoftOptions.ClientId     = ClientId_FromTenant;
                            _microsoftOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(MicrosoftAccountHandler));
                            break;

                        case GoogleDefaults.AuthenticationScheme:
                            _googleOptions.ClientId     = ClientId_FromTenant;
                            _googleOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(GoogleHandler));
                            break;

                        case WeiboAuthenticationDefaults.AuthenticationScheme:
                            _weiboOptions.ClientId     = ClientId_FromTenant;
                            _weiboOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(WeiboAuthenticationHandler));
                            break;

                        case WeixinAuthenticationDefaults.AuthenticationScheme:
                            _weixinOptions.ClientId     = ClientId_FromTenant;
                            _weixinOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(WeixinAuthenticationHandler));
                            break;

                        case QQAuthenticationDefaults.AuthenticationScheme:
                            _qqOptions.ClientId     = ClientId_FromTenant;
                            _qqOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(QQAuthenticationHandler));
                            break;

                        case GitHubAuthenticationDefaults.AuthenticationScheme:
                            _githubOptions.ClientId     = ClientId_FromTenant;
                            _githubOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(GitHubAuthenticationHandler));
                            break;

                        case FacebookDefaults.AuthenticationScheme:
                            _facebookOptions.ClientId     = ClientId_FromTenant;
                            _facebookOptions.ClientSecret = ClientSecret_FromTenant;
                            AddSchemeIfNotExists(AppSchemes, scheme, typeof(FacebookHandler));
                            break;

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

                        //case GitterAuthenticationDefaults.AuthenticationScheme:
                        //    _gitterOptions.ClientId = ClientId_FromTenant;
                        //    _gitterOptions.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 PaypalAuthenticationDefaults.AuthenticationScheme:
                        //    _paypalOptions.ClientId = ClientId_FromTenant;
                        //    _paypalOptions.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 WordPressAuthenticationDefaults.AuthenticationScheme:
                        //    _wordpressOptions.ClientId = ClientId_FromTenant;
                        //    _wordpressOptions.ClientSecret = ClientSecret_FromTenant;
                        //    break;

                        default: break;
                        }
                    }

                    var MemoryCacheOptions = new MemoryCacheEntryOptions();

                    MemoryCacheOptions.SetAbsoluteExpiration(
                        TimeSpan.FromSeconds(TenantConstant.SchemesReflushDuration));

                    _memoryCache.Set(ResetOAuthProvider_CacheKey,
                                     "1",
                                     MemoryCacheOptions);
                }
                #endregion
            }

            return(_next(context));
        }
Esempio n. 9
0
        public Task Invoke(
            HttpContext context,
            TenantDbContext _db)
        {
            var tenant = _tenantService.GetTenant(_db,
                                                  context.Request.Host.Value);

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

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

            var reflushFlag = _memoryCache.Get <string>(reflushFlagCacheKey);

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

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

                #region ResetOAuthOptions
                if (string.IsNullOrWhiteSpace(reflushFlag) && pvtModel.Properties.Count > 0)
                {
                    // 获取当前所有OAuth Scheme
                    var AllSchemes = _oauthProvider.GetAllSchemesAsync().Result.Select(x => x.Name).ToList();

                    var TenantSchemes = AppDefaultData.Tenant.OAuthHandlers.Select(x => x.Key).ToList();

                    foreach (var scheme in TenantSchemes)
                    {
                        var ClientIdKey   = $"{scheme}:ClientId";
                        var ClientIdValue = pvtModel.Properties[ClientIdKey];

                        var ClientSecretKey   = $"{scheme}:ClientSecret";
                        var ClientSecretValue = pvtModel.Properties[ClientSecretKey];

                        if (string.IsNullOrWhiteSpace(ClientIdValue) ||
                            string.IsNullOrWhiteSpace(ClientSecretValue))
                        {
                            _oauthProvider.RemoveScheme(scheme);
                            continue;
                        }

                        AppDefaultData.Tenant.TenantProperties[ClientIdKey]     = ClientIdValue;
                        AppDefaultData.Tenant.TenantProperties[ClientSecretKey] = ClientSecretValue;

                        if (!AllSchemes.Contains(scheme))
                        {
                            var authScheme = new AuthenticationScheme(scheme,
                                                                      scheme, AppDefaultData.Tenant.OAuthHandlers[scheme]);

                            _oauthProvider.AddScheme(authScheme);
                        }
                    }


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

            return(_next(context));
        }
        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));
        }
Esempio n. 11
0
 public void UnRegister()
 {
     _schemeProvider.RemoveScheme(SchemeName);
     _optionsCache.TryRemove(SchemeName);
 }