asp.net-web-api - 停止验证 Azure AD 中 Web api 应用程序的受众

标签 asp.net-web-api azure-active-directory

我有一个与 Azure AD 配合使用的 ASP.NET WEB API Core 3.1 应用程序。 我使用 Microsoft.Identity.Web 库。 我是这样设置的:

public void ConfigureServices(IServiceCollection services)
{
    Trace.TraceInformation("Configuring services");
    services.AddProtectedWebApi(Configuration, subscribeToJwtBearerMiddlewareDiagnosticsEvents: true
            )
        .AddProtectedWebApiCallsProtectedWebApi(Configuration)
        .AddInMemoryTokenCaches();
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme)
        .AddAzureADBearer(options => Configuration.Bind("AzureAd", options));
.......
}

我的应用程序是 Multi-Tenancy 的,因此我需要取消验证受众。 最近我将该库用作单独的项目,因此我可以在其源代码中更改它:

ValidateIssuer = false

但目前我使用 nuget 的库,因此我不能简单地更改源代码来避免受众(发行者)的验证。

我应该如何配置库来实现它?

最佳答案

对于 Multi-Tenancy 应用程序,请将 ValidateIssuer 设置为 false。这意味着应用程序将验证发行人。引用这个article .

JwtBearerEvents.TokenValidated 事件中验证 token 颁发者。发行人在“iss”声明中发送。

可以禁用颁发者验证,您可以引用如下代码:

public void Configure(string name, JwtBearerOptions options)
{
    options.Audience = AzureOptions.ClientId;

    options.TokenValidationParameters = new TokenValidationParameters{
        ValidateIssuer = false
    };
    options.Events = new JwtBearerEvents()
    {
        OnTokenValidated = (context) =>
        {
            if(!context.SecurityToken.Issuer.StartsWith("https://sts.windows.net/"))
                throw new SecurityTokenValidationException();
                return Task.FromResult(0);
        }
    };

    options.Authority = $"{AzureOptions.Instance}{AzureOptions.TenantId}";
}

关于asp.net-web-api - 停止验证 Azure AD 中 Web api 应用程序的受众,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61662703/

相关文章:

azure - 获取 Azure Active Directory 中的所有 AppRole 分配

azure - 使用 Graph beta 版本为企业应用程序创建新的角色分配

asp.net-mvc - MVC 中具有存储库/DTO 模式的实体的部分更新(为 API 做准备)

c# - 为什么我得到 "Culture is not supported"以及如果有的话,我应该怎么做?

c# - WebAPI 首次调用服务缓慢

c# - 如何在使用依赖注入(inject)的 ASP.NET Core 2 中使用 OIDC 登录到 Azure AD 后添加自己的声明?

azure - 当 Web 应用程序位于 AAD 组中时,用户 '<token-identified principal>' 登录失败

azure - 如何检查 Azure Active Directory 中的用户权限

ASP.NET Web Api session 与静态变量

asp.net - 将字符串数组作为参数传递给 asp.net mvc webapi 方法