使用 idToken 或 accessToken 的 Azure AD 身份验证失败。我应该使用哪一个?

Azure AD authentication failed using idToken or accessToken. Which one should I use?

在 Azure Active Directory 文档中指出:

idToken: id_tokens are sent to the client application as part of an OpenID Connect flow. They can be sent along side or instead of an access token, and are used by the client to authenticate the user.

访问令牌:Access tokens enable clients to securely call APIs protected by Azure

我正在使用 msal 将用户登录到我的 vue 应用程序(单页 Web 应用程序)并尝试获取我的 REST API.

的 accessToken

我的目标是将前端的身份验证流程与后端分开,以便将来多个客户端应用程序可以通过 accessTokens 访问 REST API。

登录时,我收到权限弹出提示,然后在 msal.aquireTokenSilent(config) 的令牌响应中收到 idToken token.idToken.rawIdToken 和 accessToken token.accessToken

我正在使用护照和 passport-azure-ad 以及 BearerStrategy 来验证作为中间件的 accessToken。如果我通过授权持有人 header 传递 token.accessToken,我会收到 authentication failed due to: invalid signature 错误。如果我通过 token.idToken.rawIdToken 相反,如果我在承载策略配置中设置 validateIssuer: true,我会收到 authentication failed due to: jwt issuer is invalid

首先,我想知道应该使用哪个令牌?两者都是有效的 jwt 令牌 (https://jwt.ms/),但它们包含不同的字段。我想现在 idToken 听起来更有前途,但我不确定这是否可行,因为我需要将前端的 clientId 指定为后端的受众字段,否则它会抛出 authentication failed due to: jwt audience is invalid .所以这不是多个客户的方式,对吧?

我们使用 ID 令牌来检查用户是否已通过身份验证并获取他们的帐户详细信息。访问令牌仅用于保护 api 调用。

您可以阅读有关 Azure 文档的更多信息,特别是:

ID Tokens should be used to validate that a user is who they claim to be and get additional useful information about them - it shouldn't be used for authorization in place of an access token.

https://docs.microsoft.com/en-us/azure/active-directory/develop/id-tokens

您可以使用 AAD 颁发的访问令牌来保护您自己的自定义网站 API。请注意,您必须首先创建一个自定义范围,然后让用户同意该范围。一旦你这样做了,你的应用程序将获得该范围的令牌(访问令牌是按资源发放的,这意味着你不能保护你的自定义 Web API 使用用于 MS Graph 的令牌,例如)。

查看我的评论 here 了解更多信息。