-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
52 lines (42 loc) · 1.21 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
package jwt
import (
"fmt"
gojwt "github.com/dgrijalva/jwt-go"
)
func SignWithHS256(claims *gojwt.StandardClaims, secret []byte) (token string, err error) {
return signWithHMAC(claims, gojwt.SigningMethodHS256, secret)
}
func VerifyWithHMAC(tokenString string, secret []byte) (*gojwt.StandardClaims, error) {
claims := &gojwt.StandardClaims{}
token, err := gojwt.ParseWithClaims(
tokenString,
claims,
func(token *gojwt.Token) (interface{}, error) {
if _, ok := token.Method.(*gojwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
return secret, nil
})
if token != nil {
if token.Valid {
return claims, nil
} else {
return nil, err
}
} else {
return nil, err
}
}
func ExtractClaims(tokenString string) (*gojwt.StandardClaims, error) {
claims := &gojwt.StandardClaims{}
_, _, err := new(gojwt.Parser).ParseUnverified(tokenString, claims)
if err != nil {
return nil, err
}
return claims, nil
}
func signWithHMAC(claims *gojwt.StandardClaims, method *gojwt.SigningMethodHMAC, secret []byte) (token string, err error) {
tokenClaims := gojwt.NewWithClaims(method, claims)
token, err = tokenClaims.SignedString(secret)
return
}