You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取多受众JWT令牌,实现Azure AD认证访问GraphAPI与自有API

解决方案

核心逻辑

OIDC体系中,Access Token是与特定资源绑定的,每个Access Token的aud(受众)声明对应一个资源标识符。Azure AD默认不会签发同时包含多个资源受众的Access Token,因此更规范的做法是在用户一次认证后,通过静默授权分别获取对应Graph API和自有API的Access Token。

具体实现步骤

1. 初始认证获取Graph API的Access Token

首先配置UserManager时,包含Graph API的权限(比如User.Read,对应Graph API的资源标识符https://graph.microsoft.com):

const oidcSetups = {
    authority: buildUrl(config.oAuthAuthority, config),
    automaticSilentRenew: false,
    client_id: config.oAuthClientId,
    loadUserInfo: true,
    redirect_uri: `${window.location.protocol}//${window.location.hostname}${window.location.port ? `:${window.location.port}` : ''}`,
    response_type: 'code',
    scope: 'openid profile email User.Read' // 包含Graph API的权限
};

const userManager = new UserManager(oidcSetups);

完成初始认证后,你会得到一个可访问Graph API的Access Token,用它调用Graph API获取用户信息即可。

2. 静默授权获取自有API的Access Token

用户已完成认证并在Azure AD存在会话的前提下,调用signinSilent方法,指定自有API的scope,无需用户再次输入凭证即可拿到对应令牌:

// 初始认证成功后,获取自有API的Access Token
async function getPrivateApiAccessToken() {
    try {
        const silentAuthResult = await userManager.signinSilent({
            scope: 'openid profile email api://mycompany.pms/mycompany.api.read'
        });
        return silentAuthResult.access_token;
    } catch (err) {
        console.error('获取自有API令牌失败:', err);
        // 静默授权失败时(如会话过期),需引导用户重新登录
        await userManager.signinRedirect();
        throw err;
    }
}

关键注意事项

  • 需确保Azure AD中,你的客户端应用已被授予Graph API的User.Read权限和自有API的mycompany.api.read权限,否则令牌请求会被拒绝。
  • 两个Access Token各自独立,需分别管理它们的过期时间,可通过automaticSilentRenew配置或手动调用静默授权来刷新令牌。

内容的提问来源于stack exchange,提问作者Stephane

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.15 22:45:31