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.
47 lines
960 B
Go
47 lines
960 B
Go
package jwt
|
|
|
|
import (
|
|
"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
|
|
}
|
|
|
|
// 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
|
|
}
|