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

65 lines
1.3 KiB
Go

4 years ago
package jwt
import (
"crypto/rsa"
4 years ago
"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
}
// 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
}
4 years ago
// 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
}