无法反序列化密钥数据 (RSA)。数据可能格式不正确

问题描述 投票:0回答:1

我有这个烧瓶端点。但 openssl 引发了一个奇怪的错误。

import jwt

@app.route('/api/secure')
def secure_endpoint():
    options = {'verify_aud': False, 'require_sub': True}
    access_token = request.headers.get('Authorization').split('Bearer ')[1]
    jwks_uri = 'https://login.microsoftonline.com/common/discovery/v2.0/keys'
    jwkeys = requests.get(jwks_uri).json()['keys']
    token_key_id = jwt.get_unverified_header(access_token)['kid']
    jwk = [key for key in jwkeys if key['kid'] == token_key_id][0]
    der_cert = b64decode(jwk['x5c'][0])
    cert = x509.load_der_x509_certificate(der_cert, default_backend())
    public_key = cert.public_key()
    pem_key = public_key.public_bytes(encoding=serialization.Encoding.PEM,
                                      format=serialization.PublicFormat.SubjectPublicKeyInfo)
    token_claims = jwt.decode(jwt=access_token, verify=False, key=pem_key,
                              audience=app_config.CLIENT_ID, algorithms=['RS256'], options=options)
    print(token_claims)

错误发生在

jwt.decode(
行。

我尝试添加填充

pem_key = pem_key.decode().split('\n-----END PUBLIC KEY-----\n')[0] + '==' + '\n-----END PUBLIC KEY-----\n'
然后出现以下错误

ValueError: ('Could not deserialize key data. The data may be in an incorrect format, it may be encrypted with an unsupported algorithm, or it may be an unsupported key type (e.g. EC curves with explicit parameters).', [_OpenSSLErrorWithText(code=75497572, lib=9, reason=100, reason_text=b'error:0480

上下文:我正在验证 azure AD (MSAL) 从 Angular 客户端生成的令牌。我无法解码令牌。请帮我。预先感谢。

RSA512 也出现此错误。使用的jwt包是

PyJwt

python azure flask jwt azure-ad-msal
1个回答
0
投票

当您处理来自 AuthenticationResult 的令牌时,需要确保令牌是

idToken
,而不是
accessToken

export type AuthenticationResult = {
    authority: string;
    uniqueId: string;
    tenantId: string;
    scopes: Array<string>;
    account: AccountInfo | null;
    idToken: string;
    idTokenClaims: object;
    accessToken: string;
    fromCache: boolean;
    expiresOn: Date | null;
    extExpiresOn?: Date;
    refreshOn?: Date;
    tokenType: string;
    correlationId: string;
    requestId?: string;
    state?: string;
    familyId?: string;
    cloudGraphHostName?: string;
    msGraphHost?: string;
    code?: string;
    fromNativeBroker?: boolean;
};

提醒一下,通过Azure SSO登录后,您将获得多个令牌,您唯一需要验证的令牌是

idToken
,因为它是为您准备的,并且不要验证
accessToken
,这是为您准备的微软图表。

我几天来一直在尝试验证

accessToken
,结果发现它不适合我们。


请注意,登录Azure SSO后,您将获得多个令牌,您需要验证的唯一令牌是

idToken
,因为它是为您而设计的,请不要验证
accessToken
,因为它是为Microsoft图形设计的。

我已经尝试了几天验证

accessToken
,结果发现它不适用于我们。

© www.soinside.com 2019 - 2024. All rights reserved.