-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
60 lines (50 loc) · 1.25 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
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"errors"
"time"
jwt "github.com/dgrijalva/jwt-go"
)
type JwtClaim struct {
Email string
CA string
jwt.StandardClaims
}
/* 로그인 후 사용할 JWT 토큰을 생성함 */
func GenerateToken(Email string, CA string) (signedToken string, err error) {
claims := &JwtClaim{ // Account ID와 만료에 대한 정보를 담고 있음
Email: Email,
CA: CA,
StandardClaims: jwt.StandardClaims{
ExpiresAt: time.Now().Local().Add(60 * time.Minute).Unix(), // 60분 뒤 만료
},
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims) // token 생성
signedToken, err = token.SignedString([]byte("SecreteCode")) // Secretecode는 토큰 자체 인증키(자체 비밀번호 느낌)
if err != nil {
return
}
return
}
/* JWT 토큰 검증 */
func ValidateToken(signedToken string) (claims *JwtClaim, err error) {
token, err := jwt.ParseWithClaims(
signedToken,
&JwtClaim{},
func(token *jwt.Token) (interface{}, error) {
return []byte("SecreteCode"), nil
},
)
if err != nil {
return
}
claims, ok := token.Claims.(*JwtClaim)
if !ok {
err = errors.New("couldn't parse claims")
return
}
if claims.ExpiresAt < time.Now().Local().Unix() {
err = errors.New("jwt is expired")
return
}
return
}