.NET Core 2.0 中的多租户授权:如何

Multi-tenant Authorization in .NET Core 2.0: How To

我想在 .NET Core 中设置多租户。基本思路是这样的:

任何使用第 3 方提供商(Azure AD、Google 等)登录的人首次需要 "register"。然后,他们的 Google 帐户将与一个用户帐户相关联。 JWT 令牌也将映射到具有特定权限的用户帐户。

我最初的尝试是做这样的事情:

services.AddAuthentication(sharedOptions =>
{
   sharedOptions.DefaultScheme  =cookieAuthenticationDefaults.AuthenticationScheme;
                sharedOptions.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme;
            })
            .AddGoogle(optoins =>  Configuration.Bind("Google", options)) 
            .AddAzureAd(options => Configuration.Bind("AzureAd", options))
            .AddCookie();

问题是现在我有多个挑战和身份验证方案,所以我的计划是删除默认方案并为用户提供一种方法 select 他们想使用什么方案。

我所做的是继承 AuthenticationService 并覆盖 AuthenticateAsyncChallengeAsyncSignInAsync。身份验证和挑战将重定向到用户将 select 他们的身份验证首选项的页面。他们的选择随后存储在 cookie 中,并用于随后对 Authenticate 和 Challenege 的调用。到目前为止一切正常,除了现在 SignInAsync 运行时没有注册的处理程序。

在这个阶段,我想知道我解决问题的方法是否正确:看起来启动应该已经注册了我需要的处理程序。我确信有一种方法可以让我根据用户的 selection 注册处理程序,但我想知道这是否正确。

通读 Microsoft 的身份文档后,似乎为了让他们的示例按书面方式工作,需要使用身份。对 AddIdentityAddDefaultTokenProviders 的调用配置默认值 以下代码将 more-or-less 按照我的要求执行(为 JWT 保留)

 //configure identity
            services.AddDbContext<ApplicationDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddIdentity<ApplicationUser, IdentityRole>()
                .AddEntityFrameworkStores<ApplicationDbContext>()
                .AddDefaultTokenProviders();

            //configure other providers
            var authSection = Configuration.GetSection("Authentication");

             var authBuilder=services.AddAuthentication()
            .AddGoogle(options =>  authSection.Bind("GooglePlus", options))
            .AddAzureAd(options => authSection.Bind("AzureAd", options));

文档是这样说的:

注意:调用AddIdentity配置默认方案设置。 AddAuthentication(string defaultScheme) 重载设置 DefaultScheme 属性;并且 AddAuthentication(Action<AuthenticationOptions> configureOptions) 重载仅设置您明确设置的属性。添加多个身份验证提供程序时,这些重载中的任何一个都应该只调用一次。对其的后续调用有可能覆盖任何先前配置的 AuthenticationOptions 属性。