0

我使用了下面来自Microsoft的 python 代码示例来尝试解码来自 Microsoft AD 的访问和身份令牌 (JWT)。我已经尝试了我可以在网上找到的所有方法来执行此操作,无论我不断收到此错误:

  File "C:\Users\Connor Johnson\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jwt.py", line 92, in decode
    jwt, key=key, algorithms=algorithms, options=options, **kwargs
  File "C:\Users\Connor Johnson\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 156, in decode
    key, algorithms)
  File "C:\Users\Connor Johnson\AppData\Local\Programs\Python\Python37\lib\site-packages\jwt\api_jws.py", line 223, in _verify_signature
    raise InvalidSignatureError('Signature verification failed')
jwt.exceptions.InvalidSignatureError: Signature verification failed

我尝试了不同的以编码为中心的解决方案,但都无济于事,此时我所能想到的是这是一个 AD 配置问题。如果我需要提供特定的 AD 设置,请告诉我。

import jwt
import sys
import requests
from cryptography.x509 import load_pem_x509_certificate
from cryptography.hazmat.backends import default_backend

PEMSTART = '-----BEGIN CERTIFICATE-----\n'
PEMEND = '\n-----END CERTIFICATE-----'

    # get Microsoft Azure public key


def get_public_key_for_token(kid):
  response = requests.get(
  'https://login.microsoftonline.com/common/.well-known/openid-configuration',
  ).json()

  jwt_uri = response['jwks_uri']
  response_keys = requests.get(jwt_uri).json()
  pubkeys = response_keys['keys']

  public_key = ''

  for key in pubkeys:
      # found the key that matching the kid in the token header
      if key['kid'] == kid:
          # construct the public key object
          mspubkey = str(key['x5c'][0])
          cert_str = PEMSTART + mspubkey + PEMEND
          cert_obj = load_pem_x509_certificate(str.encode(cert_str), default_backend())
          public_key = cert_obj.public_key()

  return public_key

# decode the given Azure AD access token


def aad_access_token_decoder(access_token):
  header = jwt.get_unverified_header(access_token)
  print(header['kid'])
  public_key = get_public_key_for_token(header['kid'])
  # the value of the databricks_resource_id is as defined above
  databricks_resource_id=<APP ID>
  decoded=jwt.decode(access_token, key = public_key, algorithms = 'RS256',
      audience = databricks_resource_id)

  for key in decoded.keys():
      print(key + ': ' + str(decoded[key]))

aad_access_token_decoder(<JWT BEARER TOKEN IN STRING>)

4

1 回答 1

0

您的应用注册配置错误。您的发行人网址、受众或其他内容设置错误。如果不了解有关应用程序注册和代码设置的更多信息,我无法告诉您更多信息。

我很确定 oidc 配置 url 中的“common”仅适用于多租户应用程序。如果您的应用不是多租户,您可以尝试在此处替换您的租户 ID。

于 2020-08-02T02:34:38.303 回答