簡體   English   中英

如何在 python 中驗證來自 AzureAD 的 JWT?

[英]How to validate a JWT from AzureAD in python?

我已經使用 AzureAD 設置了授權服務器。 為了測試它,我目前正在應用隱式流並獲取令牌和 id_token 我使用https://oidcdebugger.com/

現在我想弄清楚如何正確驗證資源服務器端的令牌。 我總是收到jose.exceptions.JWTError: Signature verification failed 你能幫我找出我做錯了什么嗎? 我對 JWT 驗證真的很陌生,可能在某個地方存在一些明顯的錯誤。

https://login.microsoftonline.com/{tenant_id}/v2.0/.well-known/openid-configuration的 OIDC 元數據端點所定義,用於簽名驗證的密鑰可在https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys 該端點上的密鑰 ID 與我的令牌標頭中的kid值匹配。 所以,我很肯定這些是我的鑰匙。 它們看起來像這樣:

{
   "kty": "RSA",
   "use": "sig",
   "kid": "<the-key-id>",
   "x5t": "<the-key-id>",
   "n": "<a-long-hash>",
   "e": "AQAB",
   "x5c": ["<a-long-hash-I-guess-thats-the-public-key"],
   "issuer": "https://login.microsoftonline.com/<my-tenant-id>/v2.0"
}

這篇文章的答案中,密鑰是使用cryptography.x509手工構建的。 我嘗試了同樣的方法,但我必須更改一些細節才能使其運行。 我是.encode字符串,我必須將一個可迭代傳遞給decode function。

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

AZURE_TENANT_ID = '<my-tenant-id>'
AZURE_KEYS = requests.get(url='<my-jwks_url>').json()['keys']

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


def decode(token: str, keys: list):
    token_header = jwt.get_unverified_header(token=token)
    x5t = token_header['x5t']

    key = [d for d in keys if d['x5t'] == x5t][0]
    mspubkey = key['x5c'][0]

    cert_str = PEMSTART + mspubkey + PEMEND
    cert_obj = load_pem_x509_certificate(cert_str.encode(), default_backend())
    public_key = cert_obj.public_key()

    return jwt.decode(
        token=token,
        subject='<my-subject>',
        audience='<my-audience>',
        issuer=f'https://sts.windows.net/{AZURE_TENANT_ID}/',
        algorithms=['RS256'],
        key=[public_key])

似乎我不應該驗證(訪問)令牌,只驗證 id_token 簽名。 使用jose的驗證也可以通過僅提供密鑰 dict 作為keys參數來工作(無需構造證書)。

顯然,來自 AzureAD 的(訪問)令牌不一定是標准的 JWT。 它只應該用於訪問 MS GraphAPI: https://github.com/AzureAD/azure-activedirectory-identitymodel-extensions-for-dotnet/issues/609#issuecomment-529537264

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM