You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
lib/jwt/jwt.go

47 lines
960 B
Go

4 years ago
package jwt
import (
"fmt"
4 years ago
"git.simts.cc/common/lib/types"
4 years ago
"github.com/dgrijalva/jwt-go"
)
// Encode jwt編碼
4 years ago
func Encode(values types.Data, key string) (string, error) {
4 years ago
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
}
// Decode jwt解碼
4 years ago
func Decode(tokenString string, key string) (types.Data, error) {
4 years ago
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. ")
}
4 years ago
return types.Data(claims), nil
4 years ago
}