Azure AD 参数值

Azure AD Parameter values

我正在处理 Azure AD 身份验证。即使我的令牌有效,我也总是收到 401。在哪里可以获取 Tenant 和 ValidAudience 的值?

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = 
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidAudience = 
                }
            });

您可以通过修改 启动方法 来提供租户和有效受众的价值,如下所示:

app.UseWindowsAzureActiveDirectoryBearerAuthentication(
            new WindowsAzureActiveDirectoryBearerAuthenticationOptions
            {
                Tenant = ConfigurationManager.AppSettings["ida:TenantId"]
                TokenValidationParameters = new System.IdentityModel.Tokens.TokenValidationParameters
                {
                    ValidAudience = ConfigurationManager.AppSettings["ida:Audience"]
                }
            });

ida:TenantId 的值将是您的 Azure AD 租户 ID。

确保在调用启动方法之前在web.config file -> app settings中添加以下键。

<appSettings>

<add key="ida:ClientId" value="[Enter the Application Id (also named ClientId) for the application]" />

<add key="ida:TenantId" value="[Enter the tenant/Directory Id name]" />

<add key="ida:Audience" value="[Enter App ID URI of your application]" />

</appSettings>

您可以从这里找到您的 Application(Client) IDTenant(Directory) ID

转到 Azure 门户 -> Azure AD -> 应用程序注册 -> 你的应用程序 -> 概述

在 Azure AD 中注册应用程序后,通过公开 API 设置应用程序 ID URI,如下所示:

ida:Audience 的值将是您的 应用程序 ID URI,其形式为 api://yourappid

确保添加所需的范围以避免 401 Error.

参考:

GitHub - Azure-Samples/active-directory-dotnet-webapi-manual-jwt-validation.

Azure Active Directory - Create Applications, Add Scopes And Add API Access (c-sharpcorner.com)

通常的 WindowsAzureActiveDirectoryBearerAuthentication 中间件使用 v2.0 端点不支持的元数据端点。相反,这个 OpenIdConnectSecurityTokenProvider 实现可用于获取和使用 OpenIdConnect 元数据文档 - 对于 v2 端点是 https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration

app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions
        {
            AccessTokenFormat = new JwtFormat(
                new TokenValidationParameters
                {
                    // Check if the audience is intended to be this application
                    ValidAudiences = new[] { clientId, "api://clientId" },

                    // Change below to 'true' if you want this Web API to accept tokens issued to one Azure AD tenant only (single-tenant)
                    // Note that this is a simplification for the quickstart here. You should validate the issuer. For details, 
                    // see https://github.com/Azure-Samples/active-directory-dotnet-native-aspnetcore
                    ValidateIssuer = false,

                },
                new OpenIdConnectSecurityTokenProvider("https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration")
            ),
        });