Multi-tenant Authentication using OWIN Pipeline
<p>I have a multi-tenant application where each tenant can define their own MetaData URl, ClientId, Authority, etc for either WsFed or OpenIdConnect(Azure) or Shibboleth(Kentor). All the tenants are stored in DB table and registered in the OwinStartup as below:</p>

<pre><code>        // Configure the db context, user manager and signin manager to use a single instance per request
        app.CreatePerOwinContext(ApplicationDbContext.Create);
        app.CreatePerOwinContext&lt;ApplicationUserManager&gt;(ApplicationUserManager.Create);
        app.CreatePerOwinContext&lt;ApplicationSignInManager&gt;(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&lt;ApplicationUserManager, ApplicationUser&gt;(
                    validateInterval: TimeSpan.FromMinutes(30),
                    regenerateIdentity: (manager, user) =&gt; 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 =&gt;
                        {
                            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 =&gt;
                        {
                            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;
        }
    }
</code></pre>

<p>When multiple orgnaizations of same provider (ADFS, Azure or Shibboleth) are enabled in Db, I get errors. I tried "app.Map" to extend it. But unsuccessful though. Also, I use below code to logout for all providers (ADFS and Azure) but logout also fails.</p>

<p>Provider is unique Authentication type I use across organizations.</p>

<pre><code>HttpContext.GetOwinContext().Authentication.SignOut(provider, Microsoft.AspNet.Identity.DefaultAuthenticationTypes.ApplicationCookie, DefaultAuthenticationTypes.ExternalCookie);
</code></pre>

<p>Looking for help / guidance.
Note: whenever new tenant gets added, am fine to recycle appdomain, not needed to dynamically rebuild the pipeline to make things complex.</p>