Skip to content

Scalar 集成 Microsoft Entra 身份验证

背景

本文适用于使用 ASP.NET Core 9 Web API 和 Scalar 替代 Swagger 的开发人员,需要配置 Microsoft Entra ID(原 Azure AD)身份验证来测试受保护的 API 端点。

问题描述

当从 Swagger/SwaggerUI 迁移到 Microsoft OpenAPI 包和 Scalar 时,虽然能够查看 API 文档和发送请求,但对于需要身份验证的 API 端点,Scalar 默认无法处理 Microsoft Entra 的身份验证流程,导致所有需要认证的请求都返回 401 未授权状态。

解决方案

步骤一:配置 OpenAPI 安全方案

首先需要在 Program.cs 中添加 OpenAPI 配置,定义 OAuth 2.0 身份验证方案:

csharp
using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.OpenApi.Models;

builder.Services.AddOpenApi(options =>
{
    options.AddDocumentTransformer((document, context, cancellationToken) =>
    {
        document.Components ??= new OpenApiComponents();
        
        // 添加 OAuth2 安全方案
        document.Components.SecuritySchemes.Add(JwtBearerDefaults.AuthenticationScheme, 
            new OpenApiSecurityScheme
            {
                Type = SecuritySchemeType.OAuth2,
                Flows = new OpenApiOAuthFlows
                {
                    AuthorizationCode = new OpenApiOAuthFlow
                    {
                        AuthorizationUrl = new Uri($"https://login.microsoftonline.com/{builder.Configuration["AzureAD:TenantId"]}/oauth2/v2.0/authorize"),
                        TokenUrl = new Uri($"https://login.microsoftonline.com/{builder.Configuration["AzureAD:TenantId"]}/oauth2/v2.0/token"),
                        Scopes = new Dictionary<string, string>
                        {
                            { builder.Configuration["AzureAd:Scopes"], "Data Access" }
                        },
                        // 启用 PKCE
                        Extensions = new Dictionary<string, IOpenApiExtension>()
                        {
                            ["x-usePkce"] = new OpenApiString("SHA-256")
                        }
                    }
                }
            });

        // 为所有操作添加安全要求
        document.SecurityRequirements.Add(new OpenApiSecurityRequirement
        {
            {
                new OpenApiSecurityScheme
                {
                    Reference = new OpenApiReference
                    {
                        Type = ReferenceType.SecurityScheme,
                        Id = JwtBearerDefaults.AuthenticationScheme
                    }
                },
                // 所需作用域
                new[] { builder.Configuration["AzureAd:Scopes"] }
            }
        });

        return Task.CompletedTask;
    });
});

步骤二:配置 Scalar API 参考

在中间件配置部分添加 Scalar 设置:

csharp
app.MapScalarApiReference(options =>
{
    options.Authentication = new ScalarAuthenticationOptions
    {
        PreferredSecurityScheme = JwtBearerDefaults.AuthenticationScheme,
        OAuth2 = new OAuth2Options
        {
            ClientId = builder.Configuration["AzureAd:ClientId"],
            Scopes = [builder.Configuration["AzureAd:Scopes"]]
        }
    };
});

步骤三:Entra ID 应用注册配置

在 Microsoft Entra 管理中心需要进行以下配置:

  1. 添加重定向 URI

    • 将 Scalar 的重定向 URI(通常是 https://localhost:<port>/scalar/v1)添加到前端应用注册的"重定向URI"部分
  2. 配置 API 权限

    • 在前端应用注册中,添加对后端 API 的权限请求
    • 在后端应用注册中,确保已公开相应的 API 作用域
  3. 使用正确的端点

    • 确保使用包含租户 ID 的端点(而非 /common 端点)
    • 格式应为:https://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/authorizehttps://login.microsoftonline.com/{tenant-id}/oauth2/v2.0/token

步骤四:应用程序配置

appsettings.json 中添加必要的配置:

json
{
  "AzureAd": {
    "TenantId": "your-tenant-id",
    "ClientId": "your-client-id",
    "Scopes": "api://your-client-id/data.read"
  }
}

验证配置

完成以上配置后,启动应用程序并访问 Scalar 界面:

  1. 在界面顶部应该能看到身份验证部分
  2. 认证类型应已预选为 OAuth2
  3. 点击"授权"按钮,系统会重定向到 Microsoft Entra 登录页面
  4. 登录后,即可成功测试需要认证的 API 端点

注意事项

  • 不要在前端代码中硬编码客户端密钥,应从安全配置源(如用户密钥、密钥保管库)获取
  • 确保前端和后端应用注册都已正确配置且权限匹配
  • 使用特定租户 ID 的端点,而非通用的 /common 端点

常见问题解决

IDX10511 签名验证失败

如果遇到 JWT 令牌验证错误,检查以下方面:

  1. 确保令牌颁发者(issuer)与 API 期望的颁发者匹配
  2. 验证前端和后端应用注册的受众(audience)配置
  3. 检查令牌签名密钥是否正确配置

重定向 URI 不匹配

确保在 Entra ID 中注册的重定向 URI 与 Scalar 实际使用的 URI 完全一致,包括协议、主机名和端口。

总结

通过正确配置 OpenAPI 安全方案、Scalar 认证选项和 Entra ID 应用注册,可以实现 Scalar 与 Microsoft Entra ID 的无缝集成,从而方便地测试需要身份验证的 API 端点。这种方法提供了安全、标准的 OAuth 2.0 授权码流程,支持 PKCE,符合现代身份验证最佳实践。