简体   繁体   中英

Python manually create jwt token without library

I want to generate jwt token manually without any library in python. I searched detailed information or tutorial for this but I couldn't. All information about jwt in python is library included. Is there any resource that I can benefit to generate jwt token in python?

PyJWT

PyJWT is a Python library that allows you to encode and decode JSON Web Tokens (JWT).

Installation:

pip install pyjwt

Tutorials for JWT authentication can be found in the official documentation.

A senior colleague taught this to me. There is no need huge libraries if you want to make a simple one.

def base64url_decode(input):
    
    return base64.urlsafe_b64decode(input+'==')
def base64url_encode(input):
    stringAsBytes = input.encode('ascii')
    stringAsBase64 = base64.urlsafe_b64encode(stringAsBytes).decode('utf-8').replace('=','')
    return stringAsBase64 


def jwt_creator(expiration, userid, userrole):
    header = {
        "alg": "HS256",
        "typ": "JWT"
    }
    payload = {'expired': expiration,
               'userid': userid,
               'userrole': userrole
               }
    secret_key = secrets.token_urlsafe(32)    
    total_params = str(base64url_encode(json.dumps(header))) + '.' + str(base64url_encode(json.dumps(payload)))
    signature = hmac.new(secret_key.encode(), total_params.encode(), hashlib.sha256).hexdigest()
    token = total_params + '.' + str(base64url_encode(signature))
    return token

I came across this SO thread because I wanted to create a JWT for Zoom without using the JWT library. As recommended by darth baba, I went through the PyJWT source code to recreate the implementation by using the default libraries. Hopefully, this helps some others in the future:

import base64
import json
import hmac
import hashlib
from datetime import datetime, timedelta

api_key = 'XXXXXX'
api_sec = 'XXXXXX'

due_date = datetime.now() + timedelta(minutes=10)
expiry = int(due_date.timestamp())

def base64url_encode(input: bytes):
    return base64.urlsafe_b64encode(input).decode('utf-8').replace('=','') 

def jwt(api_key, expiry, api_sec):
    
    segments = []
    
    header = {"typ": "JWT", "alg": "HS256"}
    payload = {"iss": api_key, "exp": expiry}
    
    json_header = json.dumps(header, separators=(",",":")).encode()
    json_payload = json.dumps(payload, separators=(",",":")).encode()
    
    segments.append(base64url_encode(json_header))
    segments.append(base64url_encode(json_payload))
    
    signing_input = ".".join(segments).encode()
    key = api_sec.encode()
    signature = hmac.new(key, signing_input, hashlib.sha256).digest()

    segments.append(base64url_encode(signature))
                    
    encoded_string = ".".join(segments)

    return encoded_string 

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