c# - 为 Multi-Tenancy .Net Core Web API 应用程序验证颁发者的适当位置

标签 c# single-page-application asp.net-core-webapi restful-authentication msal.js

我正在开发一个 Multi-Tenancy SPA 应用程序,它为数据调用后端 .Net Core Web API。前端 UI 将使用 MSAL 和 Microsoft 的 v2 公共(public)端点针对 AAD 对用户进行身份验证并获取 ID 和访问 token 。

在我的 Web API 中,我想验证颁发者,但如前所述 here ,使用公共(public)端点提供的元数据使正常的颁发者验证无法使用。

我看到有几个地方可能会覆盖或自定义 token 验证,但我不确定哪个是首选,或者这些方法中的任何一个是否会导致不良副作用。

一种方法使用 JwtBearer 选项的事件:options.Events.TokenValidated,另一种方法使用 TokenValidationParameters 的 IssuerValidator 委托(delegate)。

除了确保发行者存在于我的已验证发行者数据库中之外,我不想编写任何 token 验证逻辑。该逻辑应该放在 IssuerValidator 还是 TokenValidated 中?

我当前的代码如下所示(当前为单租户设置)

services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
   .AddJwtBearer(options =>
    {
       options.Authority = "https://myauthority.com";
       options.Audience = "https://myaudience.com/api/v1";
       options.TokenValidationParameters = new TokenValidationParameters
       {  
          ValidateIssuer = true,
          ValidIssuer = "myauthority.com",
          ValidateAudience = true,
          ValidAudience = "https://myaudience.com",
          ValidateLifetime = true,
          ValidateIssuerSigningKey = true,
        };
    });

我在使用 IssuerValidator 时遇到的一个问题是,似乎没有办法注入(inject)或传递对 dbContext 的引用,以便能够在一个数据库。

有没有人解决过这个问题或做过类似的事情?

最佳答案

您可以在 OnTokenValidated 事件中检查,要访问数据库上下文,您可以尝试:

 options.Events.OnTokenValidated = async (context) =>
   {


       var dbContext = context.HttpContext.RequestServices.GetRequiredService<BloggingContext>();
       var blogs = await dbContext.Blogs.ToListAsync();

       if (!true)
       {
           throw new SecurityTokenValidationException($"Tenant xxxxx is not registered");
       }

   };

关于c# - 为 Multi-Tenancy .Net Core Web API 应用程序验证颁发者的适当位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53989712/

相关文章:

azure - 如何使用 Azure Active Directory 设置 Ocelot Api Gateway

c# - wpf如何根据类型设置数据模板

c# - ValidateInput(false),但现在如何保持我的 HTML 输入干净?

javascript - 为什么我们需要在哈希导航 URL 中使用感叹号?

javascript - 基于单击按钮在 Div 中呈现新 View | AngularJS

c# - 是否可以从 .NET Core 中间件检索 Controller 的操作结果?

c# - ASP.Net Web Api Core - 无法在抽象基类中使用 CreatedAtRoute

c# - 如何为 List<T> 创建新的通用项?

c# - 何时正确释放 Outlook COM 对象?

asp.net-mvc - Visual Studio 不将 html/javascript 更新到服务器/浏览器