51 lines
1.4 KiB
Python
51 lines
1.4 KiB
Python
import os
|
|||
|
|
|
||
|
|
import django
|
||
|
|
|
||
|
|
from sixGuoDjango.settings import base_dir_name
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
os.environ.setdefault( key="DJANGO_SETTINGS_MODULE", value=f"{base_dir_name}.settings" )
|
||
|
|
django.setup( )
|
||
|
|
|
||
|
|
from datetime import datetime, timedelta, timezone
|
||
|
|
from pathlib import Path
|
||
|
|
|
||
|
|
from Crypto.PublicKey import RSA
|
||
|
|
from django.conf import settings
|
||
|
|
from jwt import JWT
|
||
|
|
from jwt.jwk import jwk_from_pem
|
||
|
|
from jwt.utils import get_int_from_datetime
|
||
|
|
|
||
|
|
|
||
|
|
|
||
|
|
# 创建 JWT 实例
|
||
|
|
instance = JWT( )
|
||
|
|
|
||
|
|
# 创建 payload
|
||
|
|
message = {
|
||
|
|
'iss': 'my-app',
|
||
|
|
'sub': 'user123',
|
||
|
|
'name': '张三',
|
||
|
|
'role': 'admin',
|
||
|
|
'iat': get_int_from_datetime( datetime.now( timezone.utc ) ),
|
||
|
|
'exp': get_int_from_datetime( datetime.now( timezone.utc ) + timedelta( hours=1 ) ),
|
||
|
|
}
|
||
|
|
|
||
|
|
# ✅ 正确:使用私钥进行签名
|
||
|
|
private_key_pem_私钥 = Path( "private.pem" ).read_bytes( )
|
||
|
|
私钥对象 = RSA.import_key( extern_key=private_key_pem_私钥, passphrase=settings.SECRET_KEY ).export_key( )
|
||
|
|
signing_key = jwk_from_pem( pem_content=私钥对象 )
|
||
|
|
|
||
|
|
token = instance.encode( message, signing_key, alg='RS256' ) # 注意算法名改为 RS256
|
||
|
|
print( f"生成的 JWT: {token}" )
|
||
|
|
|
||
|
|
# ✅ 正确:使用公钥进行验证
|
||
|
|
public_key_pem_公钥 = Path( "public.pem" ).read_bytes( )
|
||
|
|
verifying_key = jwk_from_pem( pem_content=public_key_pem_公钥 )
|
||
|
|
|
||
|
|
# 解码验证 JWT
|
||
|
|
received_message = instance.decode( message=token, key=verifying_key, do_time_check=True )
|
||
|
|
print( f"解码后的消息: {received_message}" )
|