RestApiv2/pkg/utils/jwt/jwtCheck.go

42 lines
1.0 KiB
Go

package jwt
import (
"fmt"
"github.com/golang-jwt/jwt/v5"
)
func ValidateToken(tokenString string, secretKey []byte) (bool, 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: %v", token.Header["alg"])
}
return secretKey, nil
})
if err != nil {
return false, err
}
if _, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return true, nil
} else {
return false, nil
}
}
func GetPayload(tokenString string, secretKey []byte) (jwt.MapClaims, 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: %v", token.Header["alg"])
}
return secretKey, nil
})
if err != nil {
return nil, err
}
if Claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
return Claims, nil
} else {
return nil, nil
}
}