Microsoft的公钥仅验证ID令牌,而不验证访问令牌。

huangapple go评论78阅读模式
英文:

Microsoft public keys only validate id token and not access tokens

问题

我正在尝试在我的Python应用中验证访问令牌,按照Microsoft的这个代码示例中的方法。所以在第99行,它使用python-jose库对令牌进行解码:

payload = jwt.decode(
                    token,
                    rsa_key,
                    algorithms=["RS256"],
                    audience=API_AUDIENCE,
                    issuer="https://sts.windows.net/" + TENANT_ID + "/"
                )

但尽管在第72行上写着:

"""Determines if the Access Token is valid"""

只有当我传递ID令牌时它才有效。每次我传递访问令牌时,都会出现以下错误:

JWTError: Signature verification failed

似乎这些URL中的公钥:

https://login.microsoftonline.com/<TENANT_ID>/discovery/v2.0/keys
https://login.microsoftonline.com/common/discovery/v2.0/keys

仅适用于ID令牌。

我确实需要验证访问令牌,因为它来自一个带有令牌授权的请求和API。如何验证访问令牌而不是ID令牌呢?

英文:

I'm trying to validate an access token in my Python app following this code sample from Microsoft So in line 99 it's decoding the token using python-jose library:

payload = jwt.decode(
                    token,
                    rsa_key,
                    algorithms=[&quot;RS256&quot;],
                    audience=API_AUDIENCE,
                    issuer=&quot;https://sts.windows.net/&quot; + TENANT_ID + &quot;/&quot;
                )

But although at line #72 it says:

> """Determines if the Access Token is valid"""

It only works if I pass the id token to it. Every time I pass the access token, I get this error:

JWTError: Signature verification failed

Seems like the public keys in this urls:

> https://login.microsoftonline.com/&lt;TENANT_ID&gt;/discovery/v2.0/keys
> https://login.microsoftonline.com/common/discovery/v2.0/keys

work only for ID Tokens.

I really need to validate the access token because its coming from a request and an API with bearer token authorisation. How can I validate the access token instead of id token?

答案1

得分: 0

感谢 @Gary,我找到了解决方案。在阅读他的博客时,我发现:

> 如果在JWT头部中获取到带有nonce字段的令牌,则它是用于Microsoft API进行验证的,将始终无法通过标准的基于签名的验证。

要获取自定义API的访问令牌,我必须在Azure门户中的注册应用程序中定义自定义范围。

当我在我的应用程序中添加了新的范围到我的OIDC配置时,我获得了一个可以通过jwt进行验证的新访问令牌。

英文:

So, thanks to @Gary I could find the solution. Reading his blog about the same issue, I found out that:

> If you get a token with a nonce field in the JWT header, then it is
> intended for Microsoft APIs to validate, and will always fail standard
> signature based validation.

To get an access token for custom APIs, I had to define a custom scope in my registered app in Azure portal.

And when I added the new scope in my OIDC configurations in my app, I got a new access token which can be verified by jwt.

huangapple
  • 本文由 发表于 2023年6月16日 00:43:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76483840.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定