之前写过一篇文章, 是介绍关于这个的, 但是今天我发现, go使用的那个库已经不再维护, 迁移到了一个新的库, 所以今天更新一下
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) } }
发表回复