我在使用 passport-azure-ad
库时遇到问题,该库在尝试验证 id_token
时抛出错误。具体的错误信息是“authentication failed due to: In _validateResponse: failed to generate PEM key due to: a key with kid %s cannot be found”
我可以看到 id_token
header 中的 kid
是一个未出现在 key 发现端点(格式为 https://login.microsoftonline.com/{tenantId}/discovery/v2.0/keys
).
为什么会发生这种情况?我无法弄清楚。
我的代码如下:
passport.use(
new OIDCStrategy({
clientID: CLIENT_ID,
clientSecret: CLIENT_SECRET,
identityMetadata: IDENTITY_METADATA_URL,
redirectUrl: SUCCESS_REDIRECT_URI,
responseMode: 'form_post',
responseType: 'code',
scope: 'email profile',
loggingLevel: 'info',
loggingNoPII: false
})
)
app.get(
'/oauthv2/login',
passport.authenticate(
'azuread-openidconnect',
{ failureRedirect: '/fail' },
(req, res) => {
// ...
}
)
)
app.post(
'/oauthv2/success',
passport.authenticate(
'azuread-openidconnect',
{ failureRedirect: '/' },
(req, res) => {
// ...
}
)
)
从 pazzport-azure-ad
日志中,我可以看到在错误发生之前执行了以下步骤:
- 收到id_token
- 收到access_token
- 收到refresh_token
- token 解码
- 研究关键
- 研究关键
- 研究关键
- 身份验证失败,原因是:在 _validateResponse 中:无法生成 PEM key ,原因是:找不到 child %s 的 key
最佳答案
所以,事实证明我在 Azure Active Directory 中创建了一个 v1 应用程序,虽然这在任何地方都不清楚并且 id_token
说它是 ver: 2.0
但是它不是....
如果您想要在 Azure AD 中使用 v2.0 应用程序,则无法从 Enterprise Applications
部分创建它,您必须使用 App registrations (Preview)
部分。
这解决了我的问题,在我删除我的应用并正确重新创建它后,id_token
包含一个有效的 KID。
希望对遇到同样问题的人有所帮助!
有用的链接:https://learn.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
如果 Azure 的任何人读到这篇文章,请知道在任何部分的标题中添加 (Preview)
意味着我将自动不点击它,因为它看起来并不重要。但是,在这种情况下,这是创建 v2.0 应用程序的唯一方法!
关于javascript - 由于 KID 错误,passport-azure-ad 无法验证 `id_token`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55472766/