从AAD Azure验证JWT access_token失败

时间:2018-11-27 23:24:49

标签: python azure jwt azure-active-directory microsoft-graph

我需要从我正在使用的服务中验证azure jwt access_token。我们目前正在向https://graph.microsoft.com/beta/me发送请求。如果请求成功,则令牌有效。不幸的是,我们将无法继续这样做。

为此,我尝试了各种想法。他们都没有成功。即使jwt.io也无法识别签名,即使jwk_uri中的可用签名之一中的jwt kidkid也匹配。

基于此博客post,我创建了以下解决方案(also available on github)

我的实现与博客文章非常相似,但有一些变化:

#!/usr/bin/env python2

import jwt
import requests
import sys

from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend


def get_public_key(access_token):
    """ Retrieve public key for access token """
    token_header = jwt.get_unverified_header(access_token)

    res = requests.get('https://login.microsoftonline.com/common/.well-known/openid-configuration')
    jwk_uri = res.json()['jwks_uri']

    res = requests.get(jwk_uri)
    jwk_keys = res.json()

    x5c = None
    # Iterate JWK keys and extract matching x5c chain
    for key in jwk_keys['keys']:
        if key['kid'] == token_header['kid']:
            x5c = key['x5c']
            break
    else:
        raise Exception('Certificate not found in {}'.format(jwk_uri))

    cert = ''.join([
        '-----BEGIN CERTIFICATE-----\n',
        x5c[0],
        '\n-----END CERTIFICATE-----\n',
    ])
    try:
        public_key =  load_pem_x509_certificate(cert.encode(), default_backend()).public_key()
    except Exception as error:
        raise Exception('Failed to load public key:', error)

    return public_key, key['kid']

def main():
    print '\n'
    if len(sys.argv) < 2 or '-h' in sys.argv:
        print 'Run it again passing acces token:\n\tpython jwt_validation.py <access_token>'
        sys.exit(1)

    access_token = sys.argv[1]
    audience = 'https://graph.microsoft.com'

    public_key, kid = get_public_key(access_token)

    try:
        jwt.decode(
            access_token,
            public_key,
            algorithms='RS256',
            audience=audience,
        )
    except Exception as error:
        print 'key {} did not worked, error:'.format(kid), error
        sys.exit(1)

    print('Key worked!')

if __name__ == '__main__':
    main()

此解决方案为有效的access_token返回Invalid Signature,并具有以下回溯:

Traceback (most recent call last):
File "jwt_validation/jwt_validation.py", line 63, in <module>
    main()
File "jwt_validation/jwt_validation.py", line 57, in main 
    audience=audience,
File "~/.pyenv/versions/jwt-validation-tool/lib/python2.7/site-packages/jwt/api_jwt.py", line 93, in decode
    jwt, key=key, algorithms=algorithms, options=options, **kwargs
File "~/.pyenv/versions/jwt-validation-tool/lib/python2.7/site-packages/jwt/api_jws.py", line 157, in decode
    key, algorithms)
File "~/.pyenv/versions/jwt-validation-tool/lib/python2.7/site-packages/jwt/api_jws.py", line 224, in _verify_signature
    raise InvalidSignatureError('Signature verification failed')
jwt.exceptions.InvalidSignatureError: Signature verification failed

任何关于我可能会做错事情的想法都会有所帮助。

2 个答案:

答案 0 :(得分:2)

经过两天的调查,我遇到了类似的问题,我发现我请求的是具有内置范围(openid和profile)的令牌,而没有任何自定义范围,这会导致发行不同受众群体的令牌(MS图),并因此使用不同的公钥签名的令牌(因为我认为发出的access_token只是委托的MS Graph范围的转发)。

我通过在我的应用程序注册中添加自定义范围(“暴露API”部分)解决了该问题,现在我的access_tokens发出了有效的审计信息,并且可以使用我的应用程序公钥检查签名。

答案 1 :(得分:0)

通常,audience声明用于指向您在Azure / Microsoft中注册的客户端应用程序的client_id。在我看来,该错误是由于jwt(可能是受众)中的声明不匹配而发生的。检查您是否为受众群体变量设置了正确的client_id