1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| package jwt
import ( "github.com/golang-jwt/jwt" "time" )
type JWTManager struct { secretKey []byte expires time.Duration }
func NewJWTManager(secretKey string, expires time.Duration) *JWTManager { return &JWTManager{ secretKey: []byte(secretKey), expires: expires, } }
func (m *JWTManager) Generate(userID string, role string) (string, error) { token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ "user_id": userID, "role": role, "exp": time.Now().Add(m.expires).Unix(), "iat": time.Now().Unix(), }) return token.SignedString(m.secretKey) }
func (m *JWTManager) Verify(tokenStr string) (*jwt.MapClaims, error) { token, err := jwt.Parse(tokenStr, 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 m.secretKey, nil }) if err != nil { return nil, err } if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid { return &claims, nil } return nil, fmt.Errorf("invalid token") }
|