1

尝试使用 ES256 算法和以下代码从服务帐户密钥创建签名 JWT 以在 GCP 中使用:

import google.auth.jwt as jwt
import google.auth.crypt
import time
import json


sa_file = 'service_account.json'
iat = time.time()
exp = iat + 3600
sa_info = json.load(open('secret.json'))
aud = 'my-audience'
url = 'my-url'

payload = {'iss': sa_info['client_email'],
           'sub': sa_info['client_email'],
           'aud': aud,
           'iat': iat,
           'exp': exp
           }
additional_headers={'kid': sa_info['private_key_id'], 'alg': 'ES256'}

signer = google.auth.crypt.ES256Signer.from_service_account_file(sa_file)
print(signer.key_id)
signed_jwt = jwt.encode(signer, payload, additional_headers, sa_info['private_key_id'])


print(signed_jwt)
print('------------')
print(sa_info['private_key'])
data = data = {
        'foo': 'bar'
    }
headers = {'Content-Type': 'application/json',
            'Authorization': 'Bearer {}'.format(signed_jwt),
            'grant_type': 'urn:ietf:params:oauth:grant-type:jwt-bearer'
           }

#response = requests.post(url, headers=headers, data=data)

#print(response.status_code, response.content) 

然而我会得到这个错误:

<ipython-input-15-06069c298e2a> in <module>
     22 signer = google.auth.crypt.ES256Signer.from_service_account_file(sa_file)
     23 print(signer.key_id)
---> 24 signed_jwt = jwt.encode(signer, payload, additional_headers, sa_info['private_key_id'])
     25 
     26 

E:\Users\Kyle\anaconda3\lib\site-packages\google\auth\jwt.py in encode(signer, payload, header, key_id)
    110 
    111     signing_input = b".".join(segments)
--> 112     signature = signer.sign(signing_input)
    113     segments.append(_helpers.unpadded_urlsafe_b64encode(signature))
    114 

E:\Users\Kyle\anaconda3\lib\site-packages\google\auth\crypt\es256.py in sign(self, message)
    118     def sign(self, message):
    119         message = _helpers.to_bytes(message)
--> 120         asn1_signature = self._key.sign(message, ec.ECDSA(hashes.SHA256()))
    121 
    122         # Convert ASN1 encoded signature to (r||s) raw signature.

TypeError: sign() missing 1 required positional argument: 'algorithm'

我也尝试过使用 PyJWT 并得到类似的错误。将算法更改为 RS256 时,它会起作用,但我仅限于使用 ES256 来签署 JWT。似乎没有地方可以传递另一个参数,但我可能忽略了一些东西。

4

0 回答 0