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 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| package jwtauth
import ( "errors" "github.com/golang-jwt/jwt" "go.uber.org/zap" "micro-shop-api/user-web/global" "time" )
type CustomClaims struct { Id uint Mobile string Nickname string jwt.StandardClaims }
func NewCustomClaimsDefault(id uint, mobile string, nickname string) *CustomClaims { beforeTime := time.Now().Unix() return &CustomClaims{ Id: id, Mobile: mobile, Nickname: nickname, StandardClaims: jwt.StandardClaims{ NotBefore: beforeTime, ExpiresAt: beforeTime + 60*60*24, Issuer: "likfees", }, } }
type JWT struct { singKey []byte }
var ( TokenExpired = errors.New("Token is expired") TokenNotValidYet = errors.New("Token not active yet") TokenMalformed = errors.New("that's not even a token") TokenInvalid = errors.New("") )
func NewJWT() *JWT { return &JWT{ singKey: []byte(global.Config.JwtInfo.SingKey), } }
func (j *JWT) CreateToken(claims CustomClaims) (token string, err error) { withClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) return withClaims.SignedString(j.singKey) }
func (j *JWT) ParseToken(token string) (*CustomClaims, error) { withClaims, err := jwt.ParseWithClaims(token, &CustomClaims{}, func(token *jwt.Token) (interface{}, error) { return j.singKey, nil }) if err != nil { if ve, ok := err.(*jwt.ValidationError); ok { zap.S().Infof("获取到 Jwt ValidationError 原:%v 错误类型:%v", err, ve.Errors) if ve.Errors&jwt.ValidationErrorMalformed != 0 { return nil, TokenMalformed } else if ve.Errors&jwt.ValidationErrorExpired != 0 { return nil, TokenExpired } else if ve.Errors&jwt.ValidationErrorNotValidYet != 0 { return nil, TokenNotValidYet } else { return nil, TokenInvalid } } return nil, TokenInvalid } if withClaims == nil { return nil, TokenInvalid }
if claims, ok := withClaims.Claims.(*CustomClaims); ok { return claims, nil } return nil, TokenInvalid
}
|