Esempio n. 1
0
 public async Task <IActionResult> AddOrUpdate(string scheme, string optionsMessage)
 {
     if (await _schemeProvider.GetSchemeAsync(scheme) == null)
     {
         _schemeProvider.AddScheme(new AuthenticationScheme(scheme, scheme, typeof(SimpleAuthHandler)));
     }
     else
     {
         _optionsCache.TryRemove(scheme);
     }
     _optionsCache.TryAdd(scheme, new SimpleOptions {
         DisplayMessage = optionsMessage
     });
     return(Redirect("/"));
 }
Esempio n. 2
0
        public void createSchemas()
        {
            using (var scope = services.CreateScope())
            {
                var accountDbContext = scope.ServiceProvider.GetRequiredService <AccountDbContext>();
                var organizations    = accountDbContext.Organizations;
                foreach (var organization in organizations)
                {
                    _logger.LogInformation("Creating Authentication Schema for organization : " + organization.Name + "");
                    _authenticationProvider.AddScheme(new AuthenticationScheme(organization.Name, organization.Name, typeof(CookieAuthenticationHandler)));



                    var _sysServices = scope.ServiceProvider.GetRequiredService <IServiceCollection>();
                    var shema        = _sysServices.AddAuthentication()
                                       .AddCookie(organization.Name, o =>
                    {
                        o.ExpireTimeSpan    = TimeSpan.FromHours(1);
                        o.LoginPath         = new PathString("/store/{OrganizationName}");
                        o.Cookie.Name       = organization.Name + " CustomerCookie";
                        o.SlidingExpiration = true;
                    });
                }
            }
        }
Esempio n. 3
0
        public MessagePump(IOptions <HttpSysOptions> options, ILoggerFactory loggerFactory, IAuthenticationSchemeProvider authentication)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }
            _options = options.Value;
            Listener = new HttpSysListener(_options, loggerFactory);
            _logger  = loggerFactory.CreateLogger <MessagePump>();

            if (_options.Authentication.Schemes != AuthenticationSchemes.None)
            {
                authentication.AddScheme(new AuthenticationScheme(HttpSysDefaults.AuthenticationScheme, displayName: _options.Authentication.AuthenticationDisplayName, handlerType: typeof(AuthenticationHandler)));
            }

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);

            if (HttpApi.IsFeatureSupported(HttpApiTypes.HTTP_FEATURE_ID.HttpFeatureDelegateEx))
            {
                var delegationProperty = new ServerDelegationPropertyFeature(Listener.RequestQueue, _logger);
                Features.Set <IServerDelegationFeature>(delegationProperty);
            }

            _maxAccepts = _options.MaxAccepts;
        }
Esempio n. 4
0
        public IISMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, IOptions <IISOptions> options, string pairingToken, IAuthenticationSchemeProvider authentication, IApplicationLifetime applicationLifetime)
        {
            if (next == null)
            {
                throw new ArgumentNullException(nameof(next));
            }
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (applicationLifetime == null)
            {
                throw new ArgumentNullException(nameof(applicationLifetime));
            }
            if (string.IsNullOrEmpty(pairingToken))
            {
                throw new ArgumentException("Missing or empty pairing token.");
            }

            _next    = next;
            _options = options.Value;

            if (_options.ForwardWindowsAuthentication)
            {
                authentication.AddScheme(new AuthenticationScheme(IISDefaults.AuthenticationScheme, _options.AuthenticationDisplayName, typeof(AuthenticationHandler)));
            }

            _pairingToken        = pairingToken;
            _applicationLifetime = applicationLifetime;
            _logger = loggerFactory.CreateLogger <IISMiddleware>();
        }
Esempio n. 5
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. 6
0
 void AddSchemeIfNotExists(List <string> AppSchemes, string oauthScheme, Type handlerType)
 {
     if (!AppSchemes.Contains(oauthScheme))
     {
         _oauthProvider.AddScheme(new AuthenticationScheme(oauthScheme, oauthScheme, handlerType));
     }
 }
Esempio n. 7
0
        public MessagePump(IOptions <HttpSysOptions> options, ILoggerFactory loggerFactory, IAuthenticationSchemeProvider authentication)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }
            if (loggerFactory == null)
            {
                throw new ArgumentNullException(nameof(loggerFactory));
            }
            _options = options.Value;
            Listener = new HttpSysListener(_options, loggerFactory);
            _logger  = loggerFactory.CreateLogger <MessagePump>();

            if (_options.Authentication.Schemes != AuthenticationSchemes.None)
            {
                authentication.AddScheme(new AuthenticationScheme(HttpSysDefaults.AuthenticationScheme, displayName: null, handlerType: typeof(AuthenticationHandler)));
            }

            Features         = new FeatureCollection();
            _serverAddresses = new ServerAddressesFeature();
            Features.Set <IServerAddressesFeature>(_serverAddresses);

            _maxAccepts = _options.MaxAccepts;
        }
Esempio n. 8
0
        public async Task <IActionResult> AddOrUpdate(string scheme, string optionsMessage)
        {
            if (await _schemeProvider.GetSchemeAsync(scheme) == null)
            {
                _schemeProvider.AddScheme(new AuthenticationScheme(scheme, scheme, typeof(GoogleHandler)));
            }
            else
            {
                _optionsCache.TryRemove(scheme);
            }
            _optionsCache.TryAdd(scheme, new GoogleOptions
            {
                SignInScheme = "Kalle",
                ClientId     = "708996912208-9m4dkjb5hscn7cjrn5u0r4tbgkbj1fko.apps.googleusercontent.com",
                ClientSecret = "wdfPY6t8H8cecgjlxud__4Gh"
                               //DisplayMessage = optionsMessage
            });

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

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

            //}, "Google");

            return(Redirect("/"));
        }
Esempio n. 9
0
        public IISHttpServer(
            IISNativeApplication nativeApplication,
            IHostApplicationLifetime applicationLifetime,
            IAuthenticationSchemeProvider authentication,
            IOptions <IISServerOptions> options,
            ILogger <IISHttpServer> logger
            )
        {
            _nativeApplication   = nativeApplication;
            _applicationLifetime = applicationLifetime;
            _logger  = logger;
            _options = options.Value;
            _serverAddressesFeature = new ServerAddressesFeature();

            if (_options.ForwardWindowsAuthentication)
            {
                authentication.AddScheme(new AuthenticationScheme(IISServerDefaults.AuthenticationScheme, _options.AuthenticationDisplayName, typeof(IISServerAuthenticationHandlerInternal)));
            }

            Features.Set <IServerAddressesFeature>(_serverAddressesFeature);

            if (_options.MaxRequestBodySize > _options.IisMaxRequestSizeLimit)
            {
                _logger.LogWarning(CoreStrings.MaxRequestLimitWarning);
            }
        }
Esempio n. 10
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);
        }
Esempio n. 11
0
        public IISHttpServer(IApplicationLifetime applicationLifetime, IAuthenticationSchemeProvider authentication, IOptions <IISOptions> options)
        {
            _applicationLifetime = applicationLifetime;
            _authentication      = authentication;
            _options             = options.Value;

            if (_options.ForwardWindowsAuthentication)
            {
                authentication.AddScheme(new AuthenticationScheme(IISDefaults.AuthenticationScheme, _options.AuthenticationDisplayName, typeof(IISServerAuthenticationHandler)));
            }
        }
Esempio n. 12
0
        public void Register(AuthenticationProvider provider)
        {
            _providerId    = provider.Id.ToString();
            _providerCache = new ProviderCache();
            SchemeName     = provider.Name;
            var scheme = new AuthenticationScheme(SchemeName, provider.DisplayName, typeof(NegotiateHandler));

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

            _optionsCache.TryAdd(SchemeName, options);
        }
        public void AddIdentityProvider <THandler, TOptions>(Guid id, TOptions options)
            where THandler : RemoteAuthenticationHandler <TOptions>
            where TOptions : RemoteAuthenticationOptions, new()
        {
            _schemeProvider.AddScheme(new AuthenticationScheme(id.ToString(), id.ToString(), typeof(THandler)));
            SetCommonProviderOptions(options);
            var postConfigure = _container.Get <IPostConfigureOptions <TOptions> >();

            postConfigure.PostConfigure(id.ToString(), options);
            var cache = _container.Get <IOptionsMonitorCache <TOptions> >();

            cache.TryAdd(id.ToString(), 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. 15
0
        public IISHttpServer(
            IISNativeApplication nativeApplication,
            IApplicationLifetime applicationLifetime,
            IAuthenticationSchemeProvider authentication,
            IOptions <IISServerOptions> options,
            ILogger <IISHttpServer> logger
            )
        {
            _nativeApplication   = nativeApplication;
            _applicationLifetime = applicationLifetime;
            _logger  = logger;
            _options = options.Value;

            if (_options.ForwardWindowsAuthentication)
            {
                authentication.AddScheme(new AuthenticationScheme(IISServerDefaults.AuthenticationScheme, _options.AuthenticationDisplayName, typeof(IISServerAuthenticationHandler)));
            }
        }
Esempio n. 16
0
        private async Task AddScheme(ExternalLoginScheme scheme)
        {
            if (!new Regex("^Scheme[0-9]$").IsMatch(scheme.Name ?? string.Empty))
            {
                throw new ArgumentException($"Scheme name '{scheme.Name}' must be like '^Scheme[0-9]$'.");
            }
            if (await schemeProvider.GetSchemeAsync(scheme.Name) != null)
            {
                throw new ArgumentException($"Scheme '{scheme.Name}' already exists.");
            }
            if (!new Regex("^[ a-zA-Z0-9]+$").IsMatch(scheme.DisplayName ?? string.Empty))
            {
                throw new ArgumentException($"Scheme display name '{scheme.DisplayName}' must be like '^[ a-zA-Z0-9]+$'.");
            }

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

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

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

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

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

            logger.LogInformation("Added external authentication {ExternalLogin} for tenant {Tenant}.", scheme.Name, resolvedTenant.TenantName);
        }
Esempio n. 17
0
        public async Task <IActionResult> Register(IndexViewModel mod)
        {
            Register     registerModel     = mod.Register;
            Organization organizationExist = await _organizationRepository.OraganizationExist(registerModel.DatabaseName);

            if (organizationExist == null)
            {
                var user = new ApplicationUser
                {
                    Email        = registerModel.Email,
                    DatabaseName = registerModel.DatabaseName,
                    Country      = registerModel.Country,
                    Language     = registerModel.Language,
                    UserName     = registerModel.UserName,
                    Organization = new Organization {
                        Name  = registerModel.DatabaseName,
                        Email = registerModel.Email
                    }
                };



                var result = await _userManager.CreateAsync(user, registerModel.Password);

                if (result.Succeeded)
                {
                    List <Task> tasks        = new List <Task>();
                    var         roleAdmin    = "Administrator";
                    var         roleEmployee = "Employee";
                    await _management.AddRoleToUserAsync(roleAdmin, user);

                    await _management.AddRoleToUserAsync(roleEmployee, user);

                    await _userManager.AddClaimAsync(user, new Claim("organization", user.DatabaseName));

                    await _userManager.AddClaimAsync(user, new Claim("organizationId", user.OrganizationId));

                    muserLogger.LogInformation("A user with a specifc roles : " + roleAdmin + " has Been Created");

                    var res = await _signInManager.PasswordSignInAsync(user.UserName, registerModel.Password,
                                                                       true, false);

                    if (res.Succeeded)
                    {
                        tasks.Add(_databaseBuilder.createModulesDatabaseAsync(registerModel.DatabaseName));
                        tasks.Add(Task.Run(() => _authenticationProvider.AddScheme(new AuthenticationScheme(registerModel.DatabaseName, registerModel.DatabaseName, typeof(CookieAuthenticationHandler)))));

                        ;

                        await Task.WhenAll(tasks);

                        using (var scope = _service.CreateScope())
                        {
                            var _sysServices = scope.ServiceProvider.GetRequiredService <IServiceCollection>();
                            var shema        = _sysServices.AddAuthentication()

                                               .AddCookie(registerModel.DatabaseName, o =>
                            {
                                o.ExpireTimeSpan    = TimeSpan.FromHours(1);
                                o.LoginPath         = new PathString("/store/{OrganizationName}");
                                o.Cookie.Name       = registerModel.DatabaseName + " CustomerCookie";
                                o.SlidingExpiration = true;
                            });
                        }
                        return(RedirectToAction("System", "App"));
                    }
                }
                var errors = result.Errors.ToList();
                foreach (var el in errors)
                {
                    ModelState.AddModelError("", el.Code);
                }
            }
            else
            {
                ModelState.AddModelError("", "This Database Name is used");
            }

            return(View());
        }
Esempio n. 18
0
 public void AddScheme(AuthenticationScheme scheme)
 {
     _inner.AddScheme(scheme);
 }
        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)
                    {
                        if (!pvtModel.Properties.ContainsKey($"{oauthScheme}:ClientId") ||
                            !pvtModel.Properties.ContainsKey($"{oauthScheme}:ClientSecret"))
                        {
                            continue;
                        }

                        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:
                            _githubOptions.ClientId     = ClientId_FromTenant;
                            _githubOptions.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:
                            _qqOptions.ClientId     = ClientId_FromTenant;
                            _qqOptions.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]));
                        }
                    }


                    var MemoryCacheOptions = new MemoryCacheEntryOptions();

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

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

            return(_next(context));
        }
Esempio n. 20
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);
            }
        }
        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("/"));
        }
Esempio n. 22
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));
        }