-
Notifications
You must be signed in to change notification settings - Fork 0
/
jwt.go
74 lines (64 loc) · 1.74 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package internet
import (
"bytes"
"errors"
"io"
"net/http"
"time"
log "github.com/Sirupsen/logrus"
"github.com/dgrijalva/jwt-go"
"github.com/getblank/blank-router/settings"
)
type blankClaims struct {
UserID string `json:"userId"`
SessionID string `json:"sessionId"`
jwt.StandardClaims
}
func getPublicRSAKey() {
publicKeyURI := settings.SRHTTPAddress + "/public-key"
log.Infof("Try to load public RSA key from '%s'", publicKeyURI)
res, err := http.Get(settings.SRHTTPAddress + "/public-key")
if err != nil {
log.Fatal("Can't get public RSA key")
panic(err)
}
defer res.Body.Close()
log.Infof("Public RSA key received from '%s'", publicKeyURI)
publicKeyLocker.Lock()
defer publicKeyLocker.Unlock()
buf := new(bytes.Buffer)
_, err = io.Copy(buf, res.Body)
if err != nil {
panic(err)
}
publicRSAKey, err = jwt.ParseRSAPublicKeyFromPEM(buf.Bytes())
if err != nil {
log.Fatal("Invalid public RSA key", err)
panic(err)
}
publicPemKey = buf.Bytes()
}
func jwtChecker(t *jwt.Token) (interface{}, error) {
claims, ok := t.Claims.(*blankClaims)
if !ok {
return nil, errors.New("invalid claims")
}
if !claims.VerifyIssuer("Blank ltd", true) {
return nil, errors.New("unknown issuer")
}
if !claims.VerifyExpiresAt(time.Now().Unix(), true) {
return nil, errors.New("token expired")
}
return publicRSAKey, nil
}
func extractAPIKeyAndUserIDromJWT(token string) (apiKey, userID string, err error) {
claims, err := extractClaimsFromJWT(token)
return claims.SessionID, claims.UserID, err
}
func extractClaimsFromJWT(token string) (claims *blankClaims, err error) {
claims = new(blankClaims)
publicKeyLocker.Lock()
defer publicKeyLocker.Unlock()
_, err = jwt.ParseWithClaims(token, claims, jwtChecker)
return claims, err
}