go gin+token(JWT)验证实现登陆验证

时间:2022-06-01 19:47:31

1.准备

?
1
2
go get github.com/dgrijalva/jwt-go
go get github.com/gin-gonic/gin

 2.代码

?
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
package main
 
import (
    "errors"
    "fmt"
    "github.com/dgrijalva/jwt-go"
    "github.com/gin-gonic/gin"
    "net/http"
    "time"
)
 
func main() {
    r := gin.Default()
    r.GET("/login/:username/:password", login)
    r.GET("/verify/:token", verify)
    r.GET("/refresh/:token", refresh)
    r.GET("/sayHello/:token", sayHello)
    r.Run(":9090")
 
    //http://localhost:9090/login/dong/123456
    //http://localhost:9090/verify/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjA1MTIyMTAsImlhdCI6MTU2MDUwODYxMCwidXNlcl9pZCI6MSwicGFzc3dvcmQiOiIxMjM0NTYiLCJ1c2VybmFtZSI6ImRvbmciLCJmdWxsX25hbWUiOiJkb25nIiwicGVybWlzc2lvbnMiOltdfQ.Esh1Zge0vO1BAW1GeR5wurWP3H1jUIaMf3tcSaUwkzA
    //http://localhost:9090/refresh/eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE1NjA1MTIyNDMsImlhdCI6MTU2MDUwODYxMCwidXNlcl9pZCI6MSwicGFzc3dvcmQiOiIxMjM0NTYiLCJ1c2VybmFtZSI6ImRvbmciLCJmdWxsX25hbWUiOiJkb25nIiwicGVybWlzc2lvbnMiOltdfQ.Xkb_J8MWXkwGUcBF9bpp2Ccxp8nFPtRzFzOBeboHmg0
}
 
const(
    ErrorReason_ServerBusy = "服务器繁忙"
    ErrorReason_ReLogin = "请重新登陆"
)
 
func sayHello(c *gin.Context) {
    strToken := c.Param("token")
    claim,err := verifyAction(strToken)
    if err != nil {
        c.String(http.StatusNotFound, err.Error())
        return
    }
    c.String(http.StatusOK, "hello,",claim.Username)
}
 
type JWTClaims struct { // token里面添加用户信息,验证token后可能会用到用户信息
    jwt.StandardClaims
    UserID      int      `json:"user_id"`
    Password    string   `json:"password"`
    Username    string   `json:"username"`
    FullName    string   `json:"full_name"`
    Permissions []string `json:"permissions"`
}
 
var (
    Secret     = "dong_tech" // 加盐
    ExpireTime = 3600        // token有效期
)
 
func login(c *gin.Context) {
    username := c.Param("username")
    password := c.Param("password")
    claims := &JWTClaims{
        UserID:      1,
        Username:    username,
        Password:    password,
        FullName:    username,
        Permissions: []string{},
    }
    claims.IssuedAt = time.Now().Unix()
    claims.ExpiresAt = time.Now().Add(time.Second * time.Duration(ExpireTime)).Unix()
    signedToken,err:=getToken(claims)
    if err!=nil{
        c.String(http.StatusNotFound, err.Error())
        return
    }
    c.String(http.StatusOK, signedToken)
}
 
func verify(c *gin.Context) {
    strToken := c.Param("token")
    claim,err := verifyAction(strToken)
    if err != nil {
        c.String(http.StatusNotFound, err.Error())
        return
    }
    c.String(http.StatusOK, "verify,",claim.Username)
}
 
func refresh(c *gin.Context) {
    strToken := c.Param("token")
    claims,err := verifyAction(strToken)
    if err != nil {
        c.String(http.StatusNotFound, err.Error())
        return
    }
    claims.ExpiresAt = time.Now().Unix() + (claims.ExpiresAt - claims.IssuedAt)
    signedToken,err:=getToken(claims)
    if err!=nil{
        c.String(http.StatusNotFound, err.Error())
        return
    }
    c.String(http.StatusOK, signedToken)
}
 
func verifyAction(strToken string) (*JWTClaims, error) {
    token, err := jwt.ParseWithClaims(strToken, &JWTClaims{}, func(token *jwt.Token) (interface{}, error) {
        return []byte(Secret), nil
    })
    if err != nil {
        return nil, errors.New(ErrorReason_ServerBusy)
    }
    claims, ok := token.Claims.(*JWTClaims)
    if !ok {
        return nil, errors.New(ErrorReason_ReLogin)
    }
    if err := token.Claims.Valid(); err != nil {
        return nil, errors.New(ErrorReason_ReLogin)
    }
    fmt.Println("verify")
    return claims, nil
}
 
func getToken(claims *JWTClaims)(string,error){
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
    signedToken, err := token.SignedString([]byte(Secret))
    if err != nil {
        return "",errors.New(ErrorReason_ServerBusy)
    }
    return signedToken,nil
}

运行结果如图:

访问接口

登陆
验证
刷新
http://localhost:9090/login/
http://localhost:9090/verify/
http://localhost:9090/refresh/

go gin+token(JWT)验证实现登陆验证

到此这篇关于go gin+token(JWT)验证实现登陆验证的文章就介绍到这了,更多相关go gin token JWT登陆验证内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://zld126126.blog.csdn.net/article/details/91997398