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

64 lines
1.3 KiB
Go

package jwt
import (
"crypto/rsa"
"fmt"
"git.simts.cc/common/lib/types"
"github.com/golang-jwt/jwt/v5"
)
// 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
}