package jwt import ( "crypto/rsa" "fmt" "git.simts.cc/common/lib/types" "github.com/dgrijalva/jwt-go" ) // Encode jwt編碼 func Encode(values types.Data, key string) (string, error) { claims := jwt.MapClaims{} for key, value := range values { claims[key] = value } tokenString, err := jwt. NewWithClaims(jwt.SigningMethodHS256, claims). SignedString([]byte(key)) if err != nil { return "", err } return tokenString, nil } // EncodeRS256 jwt編碼 func EncodeRS256(values types.Data, key *rsa.PrivateKey) (string, error) { claims := jwt.MapClaims{} for key, value := range values { claims[key] = value } tokenString, err := jwt. NewWithClaims(jwt.SigningMethodRS256, claims). SignedString(key) if err != nil { return "", err } return tokenString, nil } // Decode jwt解碼 func Decode(tokenString string, key string) (types.Data, error) { token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf("Unexpected error: %v. ", token.Header["alg"]) } return []byte(key), nil }) if err != nil { return nil, err } claims, ok := token.Claims.(jwt.MapClaims) if !ok || !token.Valid { return nil, fmt.Errorf("Token error. ") } return types.Data(claims), nil }