Golang Jwt 集成 Gin
Jwt
Github: https://github.com/golang-jwt/jwt
文档:https://pkg.go.dev/github.com/golang-jwt/jwt
拉取仓库1
go get https://github.com/golang-jwt/jwt
代码编写
配置文件
1 | jwt: |
定义 Payload 结构体 和 逻辑代码
request.go1
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
87package jwtauth
import (
"errors"
"github.com/golang-jwt/jwt"
"go.uber.org/zap"
"micro-shop-api/user-web/global"
"time"
)
// CustomClaims 自定义 Payload 信息
type CustomClaims struct {
Id uint // 用户id
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 // Jwt 密钥
}
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("") // 无效令牌
)
// NewJWT 返回一个JWT 实例
func NewJWT() *JWT {
return &JWT{
singKey: []byte(global.Config.JwtInfo.SingKey),
}
}
// CreateToken 创建新的 Token
func (j *JWT) CreateToken(claims CustomClaims) (token string, err error) {
withClaims := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return withClaims.SignedString(j.singKey)
}
// ParseToken 验证 Token
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 {
// 获取到 Jwt ValidationError 错误类型
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
}
示例
生成 Token
1 | j := jwtauth.NewJWT() |
中间件验证 Token
1 | func JwtAuth() gin.HandlerFunc { |
使用中间件1
UserRoute := router.Group("user").Use(middleware.JwtAuth())