且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-12-03 10:12:28

编辑 - 我现在可以确认此解决方案对我有用.

Edit - I can now confirm this solution is working for me.

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

I'm investigating this problem for my own project which needs to support multi tenants based on either the host name or the first folder segment of the request depending on configuration.

我还没有测试过这个,但我认为在启动时这样的代码可能会起作用:

I have not yet tested this but I'm thinking code something like this in startup might do the trick:

例如,我想为每个租户使用不同的 auth cokie 名称,我认为启动时的代码可能会起作用:

for example I want to use a different auth cokie name per tenant, and I'm thinking code in startup something like this might work:

// 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");
}