使用go解密python中制作的JWT

之前写过一篇文章, 是介绍关于这个的, 但是今天我发现, go使用的那个库已经不再维护, 迁移到了一个新的库, 所以今天更新一下

https://www.liuwh.top/%e5%9c%a8python%e4%b8%adjwt%e5%8a%a0%e5%af%86%e7%9a%84token-%e5%a6%82%e4%bd%95%e5%9c%a8go%e4%b8%ad%e8%a7%a3%e5%af%86/

python使用的库: PyJWT

go使用的库: github.com/golang-jwt/jwt/v4

在python中的制作token的代码

import jwt
import datetime
from django.conf import settings
AUTH_EXPIRE = 10*60*60
def gen_token(user_id):
    return jwt.encode({'user_id': user_id,
                       'exp': int(datetime.datetime.now().timestamp()) + AUTH_EXPIRE},
                      "你的加密秘钥", 'HS256')

在go中解密token的代码

package main

import (
	"fmt"

	"github.com/golang-jwt/jwt/v4"
)

const (
	tokenString = "python中制作的token"
)

var (
	hmacSampleSecret = []byte("你的加密秘钥")
)

func main() {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
		}
		return hmacSampleSecret, nil
	})
	fmt.Println(err)

	if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
		//claims就是你在python中加密的内容
		fmt.Println(claims)
	} else {
		fmt.Println(err)
	}
}

评论

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注