-
Notifications
You must be signed in to change notification settings - Fork 137
/
jwt.go
36 lines (31 loc) · 997 Bytes
/
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
package crypto
import (
"errors"
"fmt"
jwt "github.com/golang-jwt/jwt/v5"
)
// SigningMethod is the algorithm choosed for signing JWT.
// Currently, it is HMAC-SHA-512
var SigningMethod = jwt.SigningMethodHS512
// NewJWT creates a JWT token with the given claims,
// and signs it with the secret
func NewJWT(secret []byte, claims jwt.Claims) (string, error) {
token := jwt.NewWithClaims(SigningMethod, claims)
return token.SignedString(secret)
}
// ParseJWT parses a string and checkes that is a valid JSON Web Token
func ParseJWT(tokenString string, keyFunc jwt.Keyfunc, claims jwt.Claims) error {
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
}
return keyFunc(token)
})
if err != nil {
return err
}
if !token.Valid {
return errors.New("Invalid JSON Web Token")
}
return nil
}