How to create a signed JWT token using python

5.1k views Asked by At

Im using the jwcrypto library to create a signed JWT. The requirement is to produce a JWT signed by the private component of an RSA key. I took the steps below

Create JWK key pair

from jwcrypto import jwk,jwt
key = jwk.JWK.generate(
            kty='RSA', 
            size=2048, 
            kid='test',
            use='sig',
            e='AQAB',
            alg='RS256'
        )

private_key = key.export_private()
public_key = key.export_public(as_dict=True)

I then sent out the public key to the server and created the signed JWT like this, probably doing it wrong:

from datetime import datetime as dt

jwt_header = {
    'alg':'RS256',
    'kid':'test',
}

jwt_claims = {
    'iss':'767676',
    'sub':'test',
    'aud':'https://example.com',
    'token.aud': 'https://example.com',
    'iat':int(dt.now().timestamp()),
    'exp':int(dt.now().timestamp())+600
    
}

jwt_token = jwt.JWT(
        header = jwt_header,
        claims = jwt_claims,
    )
jwt_token.make_signed_token(key)
signed_jwt = jwt_token.serialize()

Sending JWT to Server:

headers = {
    'Accept-Encoding':'gzip,deflate',
    'Content-Type': 'application/x-www-form-urlencoded',
    'Host': 'test.example.com',
    'Connection': 'Keep-Alive',
    'User-Agent': 'TestApp/1.0.0'
    }

params = {
    'grant_type':'urn:ietf:params:oauth:grant-type:jwt-bearer',
    'assertion':signed_jwt,
    'client_id':'123456'
}

r = requests.post("https:example.com",headers=headers,params=params)

auth_data = r.json()

When I pass the signed signed_jwt to server I get an error 'Invalid Grant Type. Only jwt-bearer supported.

How can I get this working?

Also happy for an answer that uses a different library

1

There are 1 answers

15
japs On

It looks like it is more of a problem with how you interact with the server (example.com above). You should check its API documentation.

Normally the token is sent as an header like so:

headers = {
    # ...
    "Authorization": "Bearer {signed_jwt}"
}