|
|
@@ -1,14 +1,13 @@
|
|
1
|
1
|
package jwt
|
|
2
|
2
|
|
|
3
|
3
|
import (
|
|
4
|
|
- "crypto/rsa"
|
|
|
4
|
+ "fmt"
|
|
5
|
5
|
"github.com/golang-jwt/jwt/v5"
|
|
6
|
|
- "os"
|
|
7
|
6
|
"time"
|
|
8
|
7
|
)
|
|
9
|
8
|
|
|
10
|
9
|
type Jwt struct {
|
|
11
|
|
- privateKey *rsa.PrivateKey
|
|
|
10
|
+ Key []byte
|
|
12
|
11
|
TokenExpireDuration time.Duration
|
|
13
|
12
|
}
|
|
14
|
13
|
|
|
|
@@ -17,31 +16,24 @@ type UserClaims struct {
|
|
17
|
16
|
jwt.RegisteredClaims
|
|
18
|
17
|
}
|
|
19
|
18
|
|
|
20
|
|
-func NewJwt(privateKeyFile string, tokenExpireDuration time.Duration) *Jwt {
|
|
21
|
|
- privateKeyContent, err := os.ReadFile(privateKeyFile)
|
|
22
|
|
- if err != nil {
|
|
23
|
|
- panic(err)
|
|
24
|
|
- }
|
|
25
|
|
- privateKey, err := jwt.ParseRSAPrivateKeyFromPEM(privateKeyContent)
|
|
26
|
|
- if err != nil {
|
|
27
|
|
- panic(err)
|
|
28
|
|
- }
|
|
|
19
|
+func NewJwt(key string, tokenExpireDuration time.Duration) *Jwt {
|
|
29
|
20
|
return &Jwt{
|
|
30
|
|
- privateKey: privateKey,
|
|
|
21
|
+ Key: []byte(key),
|
|
31
|
22
|
TokenExpireDuration: tokenExpireDuration,
|
|
32
|
23
|
}
|
|
33
|
24
|
}
|
|
34
|
25
|
|
|
35
|
26
|
func (s *Jwt) GenerateToken(userId uint) string {
|
|
36
|
|
- t := jwt.NewWithClaims(jwt.SigningMethodRS256,
|
|
|
27
|
+ t := jwt.NewWithClaims(jwt.SigningMethodHS256,
|
|
37
|
28
|
UserClaims{
|
|
38
|
29
|
UserId: userId,
|
|
39
|
30
|
RegisteredClaims: jwt.RegisteredClaims{
|
|
40
|
31
|
ExpiresAt: jwt.NewNumericDate(time.Now().Add(s.TokenExpireDuration)),
|
|
41
|
32
|
},
|
|
42
|
33
|
})
|
|
43
|
|
- token, err := t.SignedString(s.privateKey)
|
|
|
34
|
+ token, err := t.SignedString(s.Key)
|
|
44
|
35
|
if err != nil {
|
|
|
36
|
+ fmt.Println(err)
|
|
45
|
37
|
return ""
|
|
46
|
38
|
}
|
|
47
|
39
|
return token
|
|
|
@@ -49,7 +41,7 @@ func (s *Jwt) GenerateToken(userId uint) string {
|
|
49
|
41
|
|
|
50
|
42
|
func (s *Jwt) ParseToken(tokenString string) (uint, error) {
|
|
51
|
43
|
token, err := jwt.ParseWithClaims(tokenString, &UserClaims{}, func(token *jwt.Token) (interface{}, error) {
|
|
52
|
|
- return s.privateKey.Public(), nil
|
|
|
44
|
+ return s.Key, nil
|
|
53
|
45
|
})
|
|
54
|
46
|
if err != nil {
|
|
55
|
47
|
return 0, err
|