尝试使用 MSAL 库中的代码验证我的令牌时https://github.com/AzureAD/microsoft-authentication-library-for-python
cache = _load_cache() # This web app maintains one cache per session
cca = _build_msal_app(cache=cache)
accounts = cca.get_accounts()
if accounts: # So all account(s) belong to the current signed-in user
result = cca.acquire_token_silent(scope, account=accounts[0])
_save_cache(cache)
return result
我从返回的字典中获取 id_token,该字典是 Base64 编码的。它返回一个标题:
{
"typ": "JWT",
"alg": "RS256",
"kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk"
}
有效负载:
{
"exp": 1664743047,
"nbf": 1664739447,
"ver": "1.0",
"iss": "https://******.b2clogin.com/*******/v2.0/",
"sub": "*******",
"aud": "22b52070-255a-4de8-b9ac-f6f37498e6bb",
"nonce": "a0da49a5916f3cf9a4fc7432782dba443f7a0e5dafce19f8c919b3e6a1ef67f6",
"iat": 1664739447,
"auth_time": 1664699840,
"oid": "*******",
"given_name": "Gabriel",
"tfp": "B2C_1_susi"
}
据我了解,应该有一个“x5t”密钥,其中包含我可以用来验证签名的公钥。
当我运行下面的代码来验证我的签名时,它返回为无效,这让我很困惑,因为我知道令牌来自 AAD。
from azure_ad_verify_token import verify_jwt
azure_ad_app_id = '*******'
azure_ad_issuer = 'https://exampletenant.b2clogin.com/0867afa-24e7-40e9-9d27-74bb598zzzzc/v2.0/'
azure_ad_jwks_uri = 'https://exampletenant.b2clogin.com/exampletenant.onmicrosoft.com/B2C_1_app_sign_in/discovery/v2.0/keys?appid=*********'
payload = verify_jwt(
token='<AZURE_JWT_TO_VERIFY_HERE>',
valid_audiences=[azure_ad_app_id],
issuer=azure_ad_issuer,
jwks_uri=azure_ad_jwks_uri,
verify=True,
)
尝试使用 MSAL 库中的代码验证我的令牌 https://github.com/AzureAD/microsoft-authentication-library-for-python
我从返回的字典中获取
,该字典是 Base64 编码的id_token
所以不是完整的答案,但您可以查看此存储库https://github.com/mpdavis/python-jose
您不需要使用 Python-Jose。
MSAL Python 库的最新版本还能够从返回的字典中返回
id_token_claims
。这些声明是已经为您验证的有效负载,因此您不需要这样做。
所以不是完整的答案,但你可以查看这个仓库https://github.com/mpdavis/python-jose 导入此模块“pip install python-jose[cryptography]” 您可以使用下面的代码。如果签名有效并且解密的有效负载应返回 True。
token = "Your base 64 id_token here"
rsa_key = {
"kty": "RSA",
"kid": "X5eXk4xyojNFum1kl2Ytv8dlNP4-c57dO6QGTVBwaNk",
"use": "sig",
"alg": "RS256",
"n": "your modulus",
"e": "your exponent" #for example "AQAB"
}
key = jwk.construct(rsa_key)
message, encoded_sig = token.rsplit('.', 1)
decoded_sig = base64url_decode(encoded_sig + '=' * (4 - len(encoded_sig) % 4)) # looks weird, but without added padding I got errors
res = key.verify(bytes(message, "UTF-8"), decoded_sig)
# jwt.decode(token=token, key=key.to_pem().decode(), algorithms= 'RS256') # with PEM key
allowed_aud = "22b52070-255a-4de8-b9ac-f6f37498e6bb"
payload = jwt.decode(token, rsa_key, audience=allowed_aud,algorithms='RS256') # with JWK
print(res)
print(payload)