Go语言常用的 JWT 认证函数

安装包

1
2
go get -u github.com/golang-jwt/jwt/v4
import "github.com/golang-jwt/jwt/v4"

创建 Jwt token 和解析 Jwt token 函数

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
// @package    : jwt
// @file : jwt.go
// @author : hqd8080
// @contact : hanquanding@163.com
// @time : 2024/1/02
// @description: jwt

package jwt

import (
"errors"
"github.com/golang-jwt/jwt/v4"
"time"
)

type JwtPayload struct {
UserID uint `json:"user_id"`
Username string `json:"username"`
}

type MyCustomClaims struct {
JwtPayload
jwt.RegisteredClaims
}

// CreateJwtToken 创建Jwt token
func CreateJwtToken(jwtPayload JwtPayload, accessSecret string, expires int64) (string, error) {
claims := MyCustomClaims{
JwtPayload: jwtPayload,
RegisteredClaims: jwt.RegisteredClaims{
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Hour * time.Duration(expires))),
},
}

token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(accessSecret))
}

// ParseJwtToken 解析Jwt token
func ParseJwtToken(tokenString string, accessSecret string) (*MyCustomClaims, error) {
token, err := jwt.ParseWithClaims(tokenString, &MyCustomClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(accessSecret), nil
})
if err != nil {
return nil, err
}

if claims, ok := token.Claims.(*MyCustomClaims); ok && token.Valid {
return claims, nil
}

return nil, errors.New("invalid jwt token")
}

单元测试代码

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
// @package    : jwt
// @file : jwt_test.go
// @author : hqd8080
// @contact : hanquanding@163.com
// @time : 2024/1/02
// @description: jwt_test

package jwt

import "testing"

const accessSecret = "nftmall"
const expiresHour = 2

func TestCreateJwtToken(t *testing.T) {
jwtPayload := JwtPayload{
UserID: 8080,
Username: "hqd8080",
}

token, err := CreateJwtToken(jwtPayload, accessSecret, expiresHour)
if err != nil {
t.Fatal(err)
}
t.Log(token)
}

func TestParseJwtToken(t *testing.T) {
token := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo4MDgwLCJ1c2VybmFtZSI6ImhxZDgwODAiLCJleHAiOjE3MTQxMjQ2NTF9.Mt19-NiYo1Wz62uTtRhGZ9ew9WLVMObu_uy4hWo0ebU"
jwtToken, err := ParseJwtToken(token, accessSecret)
if err != nil {
t.Fatal(err)
}
t.Log(jwtToken)
}
1
2
3
4
5
6
7
8
9
=== RUN   TestCreateJwtToken
jwt_test.go:25: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c2VyX2lkIjo4MDgwLCJ1c2VybmFtZSI6ImhxZDgwODAiLCJleHAiOjE3MTQxMjQ2NTF9.Mt19-NiYo1Wz62uTtRhGZ9ew9WLVMObu_uy4hWo0ebU
--- PASS: TestCreateJwtToken (0.00s)
PASS

=== RUN TestParseJwtToken
jwt_test.go:34: &{{8080 hqd8080} { [] 2024-04-26 17:44:11 +0800 CST <nil> <nil> }}
--- PASS: TestParseJwtToken (0.00s)
PASS