-3

EDIT

I was trying to simply generate a jwt using python-jose but I didn't find a clear example. I followed the one below, which wasn't what I really needed. After following the answer 1 I updated the code to this and it works.

!/usr/bin/env python3
from jose import jws,jwt
from Crypto.PublicKey import RSA
from time import time

# generate rsa key
key = RSA.generate(2048)
ex = int(time())
claims = {
    'iss': 'Smarneh',
    'exp': (ex + 3600),
    'sub': 42,
}


pri_key=key.exportKey()
#jws = jws.sign(claims, pri_key, algorithm='RS256')
jot =jwt.encode(claims, pri_key, algorithm='RS256')
print (jot)

I am just trying to follow this example of python-jose library

                                                                                                                                 #!/usr/bin/env python3
import jose
from Crypto.PublicKey import RSA
from time import time

# generate rsa key
key = RSA.generate(2048)
ex = int(time())
claims = {
    'iss': 'Smarneh',
    'exp': (ex + 3600),
    'sub': 42,
}

pub_jwk ={'k':key.publickey().exportKey('PEM')}

jws = jose.sign(claims, pub_jwk, alg='HS256')

and I keep getting this error :

File "./josetest.py", line 17, in jws = jose.sign(claims, pub_jwk, alg='HS256') AttributeError: module 'jose' has no attribute 'sign'

I tried to search for similar problems here but non was related to python-jose. I would appreciate any help with this.

EDIT: I am experimenting with different JWT libraries, so I have installed multiple JWT libraries. Can this be the cause of the problem?

jps
  • 20,041
  • 15
  • 75
  • 79
Alaa
  • 539
  • 3
  • 8
  • 29

1 Answers1

1

You need to import jws from the package and use jws.sign().

Try importing it like

from jose import jws

Then to sign

jws = jws.sign(claims, 'secret', alg='HS256')

Per this example https://python-jose.readthedocs.io/en/latest/jws/index.html

DoYouEvenCodeBro
  • 391
  • 3
  • 14
  • I followed your answer and the error changed to this : jose.exceptions.JWSError: Incorrect key type. Expected: 'oct', Received: None – Alaa Jan 11 '22 at 08:22
  • 1
    HS256 is a symmetric encryption algorithm, so you need to pass in a string as the key instead of your dict. Try passing in `'secret'`. – DoYouEvenCodeBro Jan 11 '22 at 08:30