PAYATHON 2026

ASP.NET Core API:复用 Entra ID 访问令牌还是自定义 JWT?

数据小陈

结论

默认不要再签发第二个 custom JWT。这个场景下,可以让 ASP.NET Core Web API 直接验证 Microsoft Entra ID 签发的 access token,再通过 scope、roles 和应用侧权限映射做授权。WinForms 端用 MSAL 获取 api://<api-client-id>/Intune.Read 的 delegated access token,之后每次调用 API 都带上它。

只有确实需要应用会话时才保留第二个 JWT,比如要统一封装遗留数据库的角色和权限、要在多个上游 API 之间维护统一会话,或者需要自定义刷新和撤销策略。此时它只应作为应用会话/授权令牌使用,用户身份仍由 Entra ID 认证。API 也应先验证 Entra ID token,再解析应用侧权限。

原因

  • Entra ID access token 已包含签名、issuer、audience、过期时间和 delegated scope,API 可以直接做标准 JWT Bearer 验证。
  • 再签发一个 JWT 相当于多做一次 token exchange,同时增加密钥管理、令牌签发、刷新、撤销和审计逻辑,攻击面也会变大。
  • 把数据库角色和权限直接写进第二个 JWT,会让权限变更滞后。更合适的做法是在授权处理阶段按需查库,并做缓存。
  • API 用 client credential 调用 Microsoft Graph / Intune 时,使用的是应用身份,不包含用户身份。如果需要代表当前用户访问 Graph,应使用 On-Behalf-Of (OBO) 流程。

推荐落地步骤

  1. 在 Entra ID 中为 API 应用公开 Intune.Read delegated scope,并让 WinForms 公共客户端请求该 scope。
  2. API 使用 Microsoft.Identity.Web 或 JwtBearer 验证 Entra ID access token,并校验 audience 和 scope。
  3. 应用侧权限不要默认写进第二个 JWT。可以用 policy-based authorization 配合自定义 IAuthorizationHandler 查询遗留数据库权限,并做短期缓存。
  4. 调用 Graph / Intune 且需要用户上下文时,API 配置 OBO,获取 Graph token 后再调用。如果确实只需要应用级权限,可以使用 client credential,但设计上要明确它不代表用户授权。

代码示例:验证 Entra ID token 并要求 scope

appsettings.json 示例:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "TenantId": "<tenant-id>",
    "ClientId": "<api-client-id>",
    "Audience": "api://<api-client-id>"
  }
}

Program.cs 示例:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Identity.Web;

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"));

builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("IntuneRead", policy =>
        policy.RequireScope("Intune.Read"));
});

控制器示例:

[ApiController]
[Route("api/[controller]")]
public class IntuneController : ControllerBase
{
    [HttpGet]
    [Authorize(Policy = "IntuneRead")]
    public IActionResult Get()
    {
        var upn = User.FindFirst("preferred_username")?.Value;
        return Ok(new { upn });
    }
}

代码示例:用自定义授权处理遗留数据库权限

public class PermissionRequirement : IAuthorizationRequirement
{
    public string Permission { get; }
    public PermissionRequirement(string permission) => Permission = permission;
}

public class PermissionHandler : AuthorizationHandler<PermissionRequirement>
{
    private readonly IPermissionService _permissions;

    public PermissionHandler(IPermissionService permissions)
    {
        _permissions = permissions;
    }

    protected override async Task HandleRequirementAsync(
        AuthorizationHandlerContext context,
        PermissionRequirement requirement)
    {
        var oid = context.User.FindFirst("oid")?.Value;
        if (string.IsNullOrEmpty(oid)) return;

        if (await _permissions.HasPermissionAsync(oid, requirement.Permission))
        {
            context.Succeed(requirement);
        }
    }
}

注册策略:

builder.Services.AddScoped<IAuthorizationHandler, PermissionHandler>();
builder.Services.AddAuthorization(options =>
{
    options.AddPolicy("CanReadIntune", policy =>
        policy.RequireAuthenticatedUser()
              .AddRequirements(new PermissionRequirement("Intune.Read")));
});

代码示例:需要用户上下文时用 OBO 调 Graph

builder.Services
    .AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAd"))
    .EnableTokenAcquisitionToCallDownstreamApi(new[] { "https://graph.microsoft.com/.default" })
    .AddInMemoryTokenCaches();
public class GraphController : ControllerBase
{
    private readonly ITokenAcquisition _tokenAcquisition;
    private readonly HttpClient _httpClient;

    public GraphController(ITokenAcquisition tokenAcquisition, HttpClient httpClient)
    {
        _tokenAcquisition = tokenAcquisition;
        _httpClient = httpClient;
    }

    [HttpGet("me")]
    [Authorize]
    public async Task<IActionResult> GetMe()
    {
        var graphToken = await _tokenAcquisition.GetAccessTokenForUserAsync(
            new[] { "https://graph.microsoft.com/.default" });

        using var request = new HttpRequestMessage(
            HttpMethod.Get, "https://graph.microsoft.com/v1.0/me");
        request.Headers.Authorization =
            new AuthenticationHeaderValue("Bearer", graphToken);

        var response = await _httpClient.SendAsync(request);
        var content = await response.Content.ReadAsStringAsync();
        return Content(content, "application/json");
    }
}

注意事项

  • 如果保留第二个 JWT,需要使用强签名密钥、短有效期、明确的 audience/issuer,并支持撤销和刷新,同时避免放入敏感信息。
  • 第二个 JWT 不能当作调用 Graph / Intune 的凭据。Graph 只接受 Entra ID 签发的 token,OBO 或 client credential 才是正确方式。
  • 如果 Graph 调用只是应用级操作,可以使用 client credential。它不保留当前用户上下文,授权设计要与此一致。
  • 应用侧权限查询应做缓存,避免每个请求都访问数据库。

备注:内容仅供参考。