java - Azure OAuth2 : can't validate access token

标签 java spring azure oauth-2.0 nimbus

我正在尝试验证 Azure OAuth2 提供的访问 token 。我正在使用 nimbus 来验证 token ,但是我不断收到“无效签名”错误。

我在某些页面上读到,如果访问 token 包含随机数,那么我将无法验证它,因为它仅供 Microsoft 内部使用。 我按照此页面 ( https://authguidance.com/azure-ad-troubleshooting/ ) 上的说明获取没有随机数的 acecss token ,但它不起作用。

我可以看到 ID token 不包含随机数,但访问 token 包含。

有谁知道如何获得可以使用 nimbus 进行验证的访问 token (没有随机数)?

最佳答案

Note that, if you validate access token generated with Microsoft Graph APIs as scope, you will get "Invalid Signature" error as it has nonce claim

我尝试在我的环境中重现相同的结果并得到以下结果:

我注册了一个 Azure AD 应用程序并添加了 Microsoft Graph API 权限,如下所示:

enter image description here

现在,我通过 Postman 使用授权代码流生成了访问 token id token ,参数如下:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:<appID>
grant_type:authorization_code
scope: https://graph.microsoft.com/User.Read openid
code:code
redirect_uri: https://jwt.ms
client_secret: <secret>

回应:

enter image description here

当我在 jwt.io 中解码上述访问 token 时网站,我也遇到了 无效签名 错误,因为它有 nonce 声明,如下所示:

enter image description here enter image description here

要在没有随机数声明的情况下获取访问 token ,请将 scope 值更改为自定义 API 而不是 Microsoft API。

我通过在应用程序中选择公开 API 添加了应用程序 ID URI 和名为 Custom.Read 的新范围,如下所示:

enter image description here

您可以在应用程序的我的 API 中找到上述范围,其名称如下:

enter image description here

现在,在应用程序的 API 权限中添加该范围,如下所示:

enter image description here

确保向添加的权限授予管理员同意,如下所示:

enter image description here

为了获取代码,我在浏览器中运行了以下授权请求,如下所示:

https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/authorize
?client_id= <appID>
&response_type=code
&redirect_uri= https://jwt.ms
&response_mode=query
&scope=api://<appID>/.default
&state=12345

回应:

enter image description here

现在,我通过 Postman 使用授权代码流将范围更改为自定义 API,生成访问 token ,如下所示:

POST https://login.microsoftonline.com/<tenantID>/oauth2/v2.0/token
client_id:<appID>
grant_type:authorization_code
scope: api://<appID>/Custom.Read openid
code:code
redirect_uri: https://jwt.ms
client_secret: <secret>

回应:

enter image description here

当我在 jwt.io 中解码上述访问 token 时网站,它没有nonce声明和签名已验证成功,如下所示:

enter image description here enter image description here

关于java - Azure OAuth2 : can't validate access token,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75535497/

相关文章:

java - 递归地在 map 上查找 "islands"区域

java - 如何使用 Spring 集成文件支持创建一种将文件从一个目录移动到另一个目录的方法?

java - 使用 @Autowired 模拟 spring jdbctemplate 问题

azure - imagemagick.net 嵌入字体

azure - MS Azure 仅向 10 台设备发送通知

node.js - 使用 Microsoft Graph 在 Teams 中创建 session 时出现 "Forbidden"错误

java - 为什么循环从对象数组中打印相同的内容?

java - Java FX Application、Scene 和 Parent 之间是什么关系?

java - 将 GWT 升级到 v2.4 时出错

java - 我如何将值分配给创建时将 String 和 ArrayList 值作为参数的对象?