更改每个请求的OWIN认证中间件(多租户,每个租户的oauth API密钥)



我有一个多租户应用程序。每个租户都可以使用OAUTH-2与Facebook、Twitter、Google等进行身份验证。对于上述服务,每个租户都有自己的API密钥。

设置OWIN管道的典型方法是在启动时"使用"认证提供商,但这会在应用启动时设置API密钥。我需要能够为每个请求更改每个oauth API使用的密钥。

        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            Provider = cookieAuthProvider,
            CookieName = "VarsityAuth",
        });
        app.UseExternalSignInCookie(DefaultAuthenticationTypes.ExternalCookie);
        app.UseMicrosoftAccountAuthentication(
            clientId: "lkjhlkjkl",
            clientSecret: "kjhjkk");

我需要能够根据租户更改每个请求的这些设置。我该怎么做呢?

编辑-我现在可以确认这个解决方案对我有效。

我正在为我自己的项目调查这个问题,该项目需要根据配置支持基于主机名或请求的第一个文件夹段的多租户。

我还没有测试过,但我认为在启动时写这样的代码可能会奏效:

例如

,我想为每个租户使用不同的认证cookie名称,我认为在启动时这样的代码可能会起作用:

// for first folder segment represents the tenant
app.Map("/branch1", app1 =>
{
    app1.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
       {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<SiteUserManager, SiteUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
    },
        CookieName = "branch1-app"
    });
});
// for when the host name of the request identifies the tenant
app.MapWhen(IsDomain1, app2 =>
{
    app2.UseCookieAuthentication(new CookieAuthenticationOptions
    {
        AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
        LoginPath = new PathString("/Account/Login"),
        Provider = new CookieAuthenticationProvider
        {
            OnValidateIdentity = SecurityStampValidator.OnValidateIdentity<SiteUserManager, SiteUser>(
            validateInterval: TimeSpan.FromMinutes(30),
            regenerateIdentity: (manager, user) => user.GenerateUserIdentityAsync(manager))
        },
        CookieName = "domain1-app"
    });

});

private bool IsDomain1(IOwinContext context)
{
    return (context.Request.Host.Value == "domain1");
}

最新更新