-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwtutils.go
52 lines (42 loc) · 1.16 KB
/
jwtutils.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 main
import (
"errors"
"github.com/golang-jwt/jwt/v5"
"log"
"net/http"
"strings"
"time"
)
const secretkeyfile = "w5a8T1V+h6aPtVyzYsH2wZkUaxOEYZyKrVYUzRQxC9E="
//generateJWT generates a JWT with user email in the claims
func generateJWT(userID string) (string, error) {
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"email": userID,
"exp": time.Now().Add(time.Minute * 10).Unix(),
})
tokenString, err := token.SignedString([]byte(secretkeyfile))
if err != nil {
return "", err
}
return tokenString, nil
}
// verifyAuthn extracts the bearer token and checks if the token is valid
func verifyAuthn(h http.Header) (any, error) {
authHeader := h.Get("Authorization")
val := strings.TrimPrefix(authHeader, "Bearer ")
if val == "" {
return nil, errors.New("AuthHeader Empty")
}
token, err := jwt.Parse(val, func(token *jwt.Token) (interface{}, error) {
return []byte(secretkeyfile), nil
})
m, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, errors.New("InvalidToken")
}
if err != nil {
log.Printf("error in validating jwt for %+v, error %+v", m["email"], err)
return nil, err
}
return m["email"], nil
}