使用OWIN管道的多租户身份验证



我有一个多租户应用程序,每个租户可以为WSFED或OpenIDConnect(Azure)或Shibboleth(Kentor)定义自己的元数据URL,客户端,权威等。所有租户都存储在DB表中,并在OwinStartup中注册:

        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
        // Enable the application to use a cookie to store information for the signed in user
        // and to use a cookie to temporarily store information about a user logging in with a third party login provider
        // Configure the sign in cookie
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            //  CookieName = "Kuder.SSO",
            LoginPath = new PathString("/Account/Login-register"),
            Provider = new CookieAuthenticationProvider
            {
                //Enables the application to validate the security stamp when the user logs in.
                //This is a security feature which is used when you change a password or add an external login to your account.  
                OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<ApplicationUserManager, ApplicationUser>(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
            }
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
    OrganizationModel objOrg = new OrganizationModel();
    var orgList = objOrg.GetOrganizationList();
    foreach (OrganizationModel org in orgList)
    {
        switch (org.AuthenticationName)
        {
            case "ADFS":
            WsFederationAuthenticationOptions objAdfs = null;
             objAdfs = new WsFederationAuthenticationOptions
                {
                    AuthenticationType = org.AuthenticationType,
                    Caption = org.Caption,
                    BackchannelCertificateValidator = null,
                    MetadataAddress = org.MetadataUrl,
                    Wtrealm = org.Realm,
                    SignOutWreply = org.Realm,
                    Notifications = new WsFederationAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            Logging.Logger.LogAndEmailException(context.Exception);
                            context.Response.Redirect(ConfigurationManager.AppSettings["CustomErrorPath"].ToString() + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    },
                    TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false },
                };
             app.UseWsFederationAuthentication(objAdfs);
                break;
            case "Azure":
                OpenIdConnectAuthenticationOptions azure = null;
                azure = new OpenIdConnectAuthenticationOptions
                {
                    AuthenticationType = org.AuthenticationType,
                    Caption = org.Caption,
                    BackchannelCertificateValidator = null,
                    Authority = org.MetadataUrl,
                    ClientId = org.IDPProvider.Trim(),
                    RedirectUri = org.Realm,
                    PostLogoutRedirectUri = org.Realm, 
                    Notifications = new OpenIdConnectAuthenticationNotifications
                    {
                        AuthenticationFailed = context =>
                        {
                            context.HandleResponse();
                            Logging.Logger.LogAndEmailException(context.Exception);
                            context.Response.Redirect(ConfigurationManager.AppSettings["CustomErrorPath"].ToString() + context.Exception.Message);
                            return Task.FromResult(0);
                        }
                    },
                    TokenValidationParameters = new TokenValidationParameters { ValidateIssuer = false },
                };
                app.UseOpenIdConnectAuthentication(azure);
                break;
            case "Shibboleth":
                var english = CultureInfo.GetCultureInfo("en-us");
                var organization = new Organization();
                organization.Names.Add(new LocalizedName("xxx", english));
                organization.DisplayNames.Add(new LocalizedName("xxx Inc.", english));
                organization.Urls.Add(new LocalizedUri(new Uri("http://www.aaa.com"), english));
                var authServicesOptions = new KentorAuthServicesAuthenticationOptions(false)
               {
                   SPOptions = new SPOptions
                   {
                       EntityId = new EntityId(org.Realm),
                       ReturnUrl = new Uri(org.Realm),
                      Organization = organization,
                   },
                   AuthenticationType = org.AuthenticationType,
                   Caption = org.Caption,
                  SignInAsAuthenticationType = "ExternalCookie",
               };
                authServicesOptions.IdentityProviders.Add(new IdentityProvider(
                new EntityId(org.IDPProvider), authServicesOptions.SPOptions)
                 {
                     MetadataLocation = org.MetadataUrl,
                     LoadMetadata = true,
                    SingleLogoutServiceUrl = new Uri(org.Realm),
                 });
                app.UseKentorAuthServicesAuthentication(authServicesOptions);
                break;
            default:
                break;
        }
    }

在DB中启用了同一提供商(ADF,Azure或Shibboleth)的多个orgnaization(ADF,Azure或Shibboleth)时,我会遇到错误。我尝试了" app.map"将其扩展。但是不成功。另外,我使用以下代码注销所有提供商(ADF和Azure),但注销也失败了。

提供商是唯一的身份验证类型I跨组织使用。

HttpContext.GetOwinContext().Authentication.SignOut(provider, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);

寻求帮助/指导。注意:每当添加新租户时,都可以回收AppDomain,不需要动态重建管道以使事情变得复杂。

kentor.authservices中间件支持多个实例,但是您需要为每个实例分配特定的ModulePath。否则,第一个kentor.authservices中间件将处理所有传入请求,并在配置其他实例的IdentityProviders的消息上丢弃错误。

我知道其他一些武士馆提供商具有相似的"隐藏"端点,这些端点在回调过程中使用,但我不知道它们是否加载了多个中间件实例。

作为替代方案,kentor.authservices中间件还支持在一个实例中注册多个身份提供者。然后,您可以在运行时添加和rmove IdentityProvider实例到KentorAuthServicesAuthenticationOptions,并立即生效。但是,如果您将每个租户使用一个中间件作为其他协议。

,这可能不是理想的解决方案。

是否可以根据app.mapwhen(" tenant1",ctx => ctx.configurespecifictenant)在app.mapwhen中的条件中创建不同的OWIN管道。

MAP当时也接受一个功能,因此您可以将其基于其他条件,例如列表上的foreach迭代的子域。

最新更新