G
G
gkgkai6662020-10-31 15:21:53
Python
gkgkai666, 2020-10-31 15:21:53

How to correctly create a JWT in python (python dict acts as a secret)?

I'm trying to write a bot for some exchange site.
The exchange provides a key of the following form:

{"kty":"EC",
       "alg":"ES256",
       "crv":"P-256",
       "x":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
       "y":"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
       "d":"ddddddddddddddddddddddddddddddddddddddddddd"}

I'm trying like this:
import jwt
import base64
import json

key = {"kty":"EC",
       "alg":"ES256",
       "crv":"P-256",
       "x":"q4WByX5XVZlfqcLGRNJ5eG5AdAzdkRnBs4feaiZdUtI",
       "y":"xbdu5Mzz87Zln6-HuVHZnBVTY-yKzDa2ZWuW9-ZT3PU",
       "d":"34IN2FU6bvabY1Kn5esjFEaRzLJLe4Ny4zDKMsj6Vn0"}

key2 = base64.urlsafe_b64encode(bytes(json.dumps(key), 'utf-8'))


def create_token(key):
    try:
       return jwt.encode({'some': 'payload'}, key, algorithm='ES256')
    except Exception as e:
       print(e)


print(create_token(key))
print(create_token(key2))

And I get:
Expecting a PEM-formatted key.
None
Could not deserialize key data.
None


I'm trying an example from the finished implementation :
from bitzlato import Bitzlato

key = {
        "kty":"EC",
       "alg":"ES256",
       "crv":"P-256",
       "x":"xxxxxxxxxxx",
       "y":"yyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyyy",
       "d":"dddddddddddddddddddddddddddddddddddddd"
}


bot = Bitzlato(parameters=key, email="[email protected]") #  Token parameter 'kid' should be 1
result = bot.get_all_orders(cryptocurrency='BTC', currency='RUB', is_owner_active=True, limit=20,
                            pay_method='443', order_type='purchase')
print(result)

and I get an error:
Traceback (most recent call last):
  File "...", line 164, in _sign_header_and_claims
    signature = key.sign(signing_input)
  File "...", line 90, in sign
    signature = self.prepared_key.sign(msg, ec.ECDSA(self.hash_alg()))
AttributeError: '_EllipticCurvePublicKey' object has no attribute 'sign'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "...", line 16, in <module>
    pay_method='443', order_type='purchase')
  File "...", line 32, in get_all_orders
    "Authorization": "Bearer " + self.connector()
  File "...", line 26, in connector
    token = jws.sign(claims, key, headers={"kid": self.kid}, algorithm=ALGORITHMS.ES256)
  File "...", line 46, in sign
    signed_output = _sign_header_and_claims(encoded_header, encoded_payload, algorithm, key)
  File "...", line 166, in _sign_header_and_claims
    raise JWSError(e)
jose.exceptions.JWSError: '_EllipticCurvePublicKey' object has no attribute 'sign'

Please tell me a working way to create a JWT from a dictionary key / a way to solve one of the above problems.
Thanks in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alfss, 2020-10-31
@alfss

getting a token

dt = datetime.datetime.now()
ts = time.mktime(dt.timetuple())
claims = {
   "email": self.email,
   "aud": "usr",
   "iat": int(ts),
   "jti": hex(random.getrandbits(64)) 
}
key = self.key
token = jws.sign(claims, key, headers={"kid": self.kid}, algorithm=ALGORITHMS.ES256

request
requests.get('https://bitzlato.com/api/p2p/exchange/dsa/', headers={
            "Authorization": "Bearer " + token
        },
            params={
                "cryptocurrency": f'{cryptocurrency}',
                "currency": f"{currency}",
                "type": f"{order_type}",  # purchase, selling
                "isOwnerActive": True,
                "limit": 20,
                "paymethod": f'{pay_method}'
        })

the jws code is here https://github.com/mpdavis/python-jose/blob/master...
All this was in the links you specified, all this could be viewed and understood.
Also, apparently you were given incorrect information or you read the "documentation" wrong, you need a JWS token.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question