Creazione di una chiave RSA per JWT

Come creare una chiave funzionante con jwt

ssh-keygen -t rsa -b 4096 -m PEM -f id_rsa_development.key

openssl rsa -in id_rsa_development.key -pubout -outform PEM -out id_rsa_development.key.pub

Fonte:

https://gist.github.com/ygotthilf/baa58da5c3dd1f69fae9

Codice d’esempio di come usare la chiave pubblica e privata.

from datetime import datetime, timedelta
import jwt

def test_hs():
    key = 'secret'
    encoded = jwt.encode({'some' : 'payload'}, key, algorithm='HS256')
    print(encoded)
    decoded = jwt.decode(encoded, key, algorithms='HS256')
    print(decoded)

def test_rsa():
    with open('private.key', 'rb') as private_file:
        private_key = private_file.read()

        with open('public.pub', 'rb') as public_file:
            public_key = public_file.read()
            # print(private_key)
            # print(public_key)
            payload = {
            'username' : 'auguste',
            'iat' : datetime.utcnow(),
            'exp' : datetime.utcnow() + timedelta(days = 2),
            }
            encoded = jwt.encode(payload, private_key, algorithm='RS256')
            print(jwt.get_unverified_header(encoded))
            print(f'Encoded : {encoded}')
            print(type(encoded))
            #print(f'Bearer {encoded.decode("utf8")}')

            decoded = jwt.decode(encoded, public_key, algorithms='RS256')
            print(f'Decoded : {decoded}')

test_rsa()