zhangzengfei
2023-08-11 bc0b7e914a378b2c40f9d2ec2470b61a19c18288
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
package util
 
import (
    "time"
 
    "plc-recorder/config"
 
    "github.com/golang-jwt/jwt/v4"
)
 
type CustomClaims struct {
    BaseClaims
    jwt.StandardClaims
}
 
type BaseClaims struct {
    UserId   string
    Username string
    ParentId string
}
 
func CreateToken() (string, error) {
    baseClaims := BaseClaims{
        UserId:   "plc-recorder",
        Username: "plc-recorder",
        ParentId: config.Options.ParentId,
    }
    claims := CustomClaims{
        BaseClaims: baseClaims,
        StandardClaims: jwt.StandardClaims{
            NotBefore: time.Now().Unix() - 1000,               // 签名生效时间
            ExpiresAt: time.Now().Add(1 * time.Minute).Unix(), // 过期时间
            Issuer:    "plc-recorder",                         // 签名的发行者
        },
    }
 
    token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
 
    signKey := []byte(config.Options.JWTKey)
 
    return token.SignedString(signKey)
}