You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中验证Bearer Token?密钥获取及其他验证方法

关于Azure AD OAuth2令牌验证的密钥获取与替代方法

一、密钥key的获取方式

你通过客户端凭证流获取的是Azure AD签发的RS256签名JWT,验证时需要用到Azure AD的公钥,而非你的客户端密钥。具体获取步骤如下:

  • 访问Azure AD的公钥端点:https://login.microsoftonline.com/{TENANT_ID}/discovery/v2.0/keys,将{TENANT_ID}替换为代码中config_data['TENANT']对应的租户ID。
  • 从返回的JSON数据里,找到与令牌kid(密钥ID)匹配的公钥,转换为PEM格式后,即可作为jwt.decode的key参数使用。

可以用代码自动完成公钥获取与匹配:

import jwt
import requests

def get_azure_ad_public_keys(tenant_id):
    keys_url = f"https://login.microsoftonline.com/{tenant_id}/discovery/v2.0/keys"
    response = requests.get(keys_url)
    return response.json()["keys"]

def validate_token(token, tenant_id):
    keys = get_azure_ad_public_keys(tenant_id)
    # 提取令牌头中的kid
    header = jwt.get_unverified_header(token)
    kid = header["kid"]
    # 匹配对应公钥
    matching_key = next(key for key in keys if key["kid"] == kid)
    # 转换为RSA公钥对象
    public_key = jwt.algorithms.RSAAlgorithm.from_jwk(matching_key)
    # 验证令牌,同时校验issuer和audience
    decoded = jwt.decode(
        token,
        public_key,
        algorithms=["RS256"],
        issuer=f"https://login.microsoftonline.com/{tenant_id}/v2.0",
        audience=config_data['RESOURCE']  # 需与获取令牌时的resource参数一致
    )
    return decoded

二、其他验证方法

  • 使用Microsoft官方库:用msal(Microsoft Authentication Library)处理令牌验证,它会自动管理公钥与校验逻辑,比手动解析更可靠:
    from msal import PublicClientApplication
    
    def validate_with_msal(token, tenant_id, client_id, resource):
        app = PublicClientApplication(client_id, authority=f"https://login.microsoftonline.com/{tenant_id}")
        try:
            claims = app.validate_id_token(token, audience=resource)
            return claims
        except Exception as e:
            print(f"令牌验证失败: {e}")
            return None
    
  • 临时测试工具:如果只是临时验证令牌,可以用JWT解析工具直接输入令牌,工具会自动加载对应公钥完成验证,但生产环境不建议使用这种方式。

内容的提问来源于stack exchange,提问作者S Andrew

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 16:52:40