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

72 lines
1.6 KiB
Go

package jwt
import (
"crypto/rsa"
"errors"
"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 k, v := range values {
claims[k] = v
}
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodHS256, claims).
SignedString([]byte(key))
if err != nil {
return "", fmt.Errorf("failed to sign JWT with HS256: %w", err)
}
return tokenString, nil
}
// EncodeRS256 jwt編碼
func EncodeRS256(values types.Data, key *rsa.PrivateKey) (string, error) {
claims := jwt.MapClaims{}
for k, v := range values {
claims[k] = v
}
tokenString, err := jwt.NewWithClaims(jwt.SigningMethodRS256, claims).
SignedString(key)
if err != nil {
return "", fmt.Errorf("failed to sign JWT with RS256: %w", 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 signing method: %w", token.Header["alg"])
}
return []byte(key), nil
})
if err != nil {
return nil, fmt.Errorf("failed to parse JWT: %w", err)
}
if token == nil || !token.Valid {
return nil, fmt.Errorf("invalid token or claims")
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, fmt.Errorf("failed to parse token claims")
}
return types.Data(claims), nil
}
// IsExpired 檢查 token 是否過期
func IsExpired(err error) bool {
return errors.Is(err, jwt.ErrTokenExpired)
}