首页 > 解决方案 > Microsoft Graph 的 MSAL 配置

问题描述

我想使用 MSAL 获取 Graph API 的令牌,但为什么我的令牌受众总是指出我的客户端 ID 我是否需要更改流程才能获取 MSAL 的令牌?当我尝试使用密码 grant_type 从邮递员那里获取令牌时,受众是 Microsoft graph。这是我的配置

export const authProvider = new MsalAuthProvider({
    auth: {
        authority: "https://login.microsoftonline.com/tenantId",
        clientId: "ClientId",
        postLogoutRedirectUri: window.location.origin,
        redirectUri: window.location.origin,
        validateAuthority: true,

        // After being redirected to the "redirectUri" page, should user
        // be redirected back to the Url where their login originated from?
        navigateToLoginRequestUrl: true
    },
    cache: {
        cacheLocation: 'localStorage',
        storeAuthStateInCookie: false
    }
},
    {
        scope: ["https://graph.microsoft.com/.default", "user.read"],
        extraQueryParameters: { domain_hint: 'organizations' }
    },
    {
        loginType: LoginType.Redirect,

        tokenRefreshUri: window.location.origin + "/auth.html"
    },


)

这就是我获得令牌的方式

   const token = await authProvider.getIdToken();
        const idToken = token.idToken.rawIdToken;

这是获得 Microsoft Graph 的请求 在此处输入图像描述

我错的部分在哪里?是我的配置还是我获取令牌的方式?

标签: javascriptreactjsazure-active-directorymsal

解决方案


很简单:这是因为您获得了一个ID Token,它不能用于访问受保护的资源(例如 MS Graph),因为:

  1. ID 令牌的“受众”( aud) 是请求它的客户端应用程序。
  2. ID 令牌没有范围 ( scp) 声明,因此无法在v2 端点中交换资源。

您的配置至少还有 1 个问题:

{
    scope: ["https://graph.microsoft.com/.default", "user.read"],
    extraQueryParameters: { domain_hint: 'organizations' }
},

/.default范围允许您一次性请求在 Portal 上添加的所有静态权限。/.default范围不能/不应与其他范围结合,尤其是v2user.read.

在此处阅读有关如何使用资源和范围的更多信息(它适用于 MSAL.js,但适用相同的原则)。


推荐阅读