github.com/zhiqiangxu/util@v0.0.0-20230112053021-0a7aee056cd5/crypto/claim/signer.go (about) 1 package claim 2 3 import ( 4 "crypto/rsa" 5 "fmt" 6 "time" 7 8 "github.com/dgrijalva/jwt-go" 9 ) 10 11 // Signer for claimer 12 type Signer struct { 13 expire time.Duration 14 method jwt.SigningMethod 15 signKey *rsa.PrivateKey 16 } 17 18 // NewSigner is ctor for Signer 19 func NewSigner(expire time.Duration, signKey *rsa.PrivateKey) (s *Signer, err error) { 20 signingAlgorithm := "RS256" 21 method := jwt.GetSigningMethod(signingAlgorithm) 22 if method == nil { 23 err = fmt.Errorf("invalid signingAlgorithm:%s", method) 24 return 25 } 26 s = &Signer{expire: expire, method: method, signKey: signKey} 27 return 28 } 29 30 const ( 31 // ExpireATKey for expire_at 32 ExpireATKey = "expire_at" 33 // CreatedKey for created 34 CreatedKey = "created" 35 ) 36 37 // Sign claims 38 func (s *Signer) Sign(values map[string]interface{}) (tokenString string, err error) { 39 40 tokenString, err = sign(values, s.expire, s.method, s.signKey) 41 return 42 } 43 44 func sign(values map[string]interface{}, expire time.Duration, method jwt.SigningMethod, signKey interface{}) (tokenString string, err error) { 45 claims := jwt.MapClaims{ 46 ExpireATKey: time.Now().Add(expire).Unix(), 47 CreatedKey: time.Now().Unix(), 48 } 49 for k, v := range values { 50 if _, ok := claims[k]; ok { 51 err = fmt.Errorf("%s is reserved for claims", k) 52 return 53 } 54 claims[k] = v 55 } 56 token := jwt.NewWithClaims(method, claims) 57 // Sign and get the complete encoded token as a string using the secret 58 tokenString, err = token.SignedString(signKey) 59 return 60 }