-
Notifications
You must be signed in to change notification settings - Fork 17
/
jwt.go
48 lines (38 loc) · 1.11 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 jwt
import (
"errors"
"strings"
"github.com/dgrijalva/jwt-go"
"github.com/hadihammurabi/belajar-go-rest-api/internal/entity"
)
func CreateJWTWithClaims(secret string, claims *entity.JWTClaims) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
return token.SignedString([]byte(secret))
}
func JWTFromHeader(auth string) (string, string, error) {
authSplitted := strings.Split(auth, " ")
if len(authSplitted) == 2 {
return authSplitted[0], authSplitted[1], nil
}
return "", "", errors.New("invalid token")
}
func VerifyJWT(token string, secret string) (*jwt.Token, error) {
parsed, err := jwt.ParseWithClaims(token, &entity.JWTClaims{}, func(t *jwt.Token) (any, error) {
return []byte(secret), nil
})
if err != nil {
return nil, err
}
return parsed, nil
}
func GetJWTData(token string, secret string) (*entity.JWTClaims, error) {
tokenVerified, err := VerifyJWT(token, secret)
if err != nil {
return nil, err
}
claims, ok := tokenVerified.Claims.(*entity.JWTClaims)
if !ok && !tokenVerified.Valid {
return nil, errors.New("invalid token")
}
return claims, nil
}