forked from iron-io/functions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjwt.go
49 lines (39 loc) · 1.09 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
package common
import (
"errors"
"net/http"
"time"
jwt "github.com/dgrijalva/jwt-go"
"github.com/dgrijalva/jwt-go/request"
)
func AuthJwt(signingKey string, req *http.Request) error {
if signingKey == "" {
return nil
}
extractor := request.AuthorizationHeaderExtractor
tokenString, err := extractor.ExtractToken(req)
if err != nil {
return err
}
token, err := jwt.ParseWithClaims(tokenString, &jwt.StandardClaims{}, func(token *jwt.Token) (interface{}, error) {
return []byte(signingKey), nil
})
if err != nil {
return err
}
if _, ok := token.Claims.(*jwt.StandardClaims); ok && token.Valid {
return nil
}
return errors.New("Invalid token")
}
func GetJwt(signingKey string, expiration int) (string, error) {
now := time.Now().Unix()
claims := &jwt.StandardClaims{
ExpiresAt: time.Unix(now, 0).Add(time.Duration(expiration) * time.Second).Unix(),
IssuedAt: now,
NotBefore: time.Unix(now, 0).Add(time.Duration(-1) * time.Minute).Unix(),
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
ss, err := token.SignedString([]byte(signingKey))
return ss, err
}