-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
48 lines (39 loc) · 1.18 KB
/
jwt.go
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
package components
import (
"fmt"
"time"
"strconv"
jwt "github.com/dgrijalva/jwt-go"
"github.com/hjhcode/deploy-web/common/g"
)
var mySigningKey = "let's to change the world!"
func CreateToken(userId int64) (string, error) {
cfg := g.Conf()
claims := jwt.MapClaims{
"uid": strconv.FormatInt(userId, 10),
"exp": time.Now().Add(time.Hour * 24 * time.Duration(cfg.Jwt.MaxEffectiveTime)).Unix(),
}
var signingMethod *jwt.SigningMethodHMAC
switch cfg.Jwt.EncodeMethod {
case "HS256":
signingMethod = jwt.SigningMethodHS256
case "HS384":
signingMethod = jwt.SigningMethodHS384
case "HS512":
signingMethod = jwt.SigningMethodHS512
default:
signingMethod = jwt.SigningMethodHS256
}
token := jwt.NewWithClaims(signingMethod, claims)
return token.SignedString([]byte(mySigningKey))
}
func RequireTokenAuthentication(tokenStr string) (bool, string) {
token, _ := jwt.ParseWithClaims(tokenStr, jwt.MapClaims{}, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("error")
}
return []byte(mySigningKey), nil
})
userId, _ := token.Claims.(jwt.MapClaims)["uid"].(string)
return token.Valid, userId
}