简体   繁体   中英

How to create a signed JWT token using python

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. 'Invalid Grant Type. Only jwt-bearer supported.

How can I get this working?

Also happy for an answer that uses a different library

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}"
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM