-
Notifications
You must be signed in to change notification settings - Fork 13
/
token_validator_jwt.go
66 lines (53 loc) · 1.62 KB
/
token_validator_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
package server
import (
"crypto/rsa"
"io/ioutil"
"github.com/cloudfoundry/bosh-utils/errors"
"github.com/dgrijalva/jwt-go"
)
const (
expectedScope = "config_server.admin"
)
type JwtTokenValidator struct {
verificationKey *rsa.PublicKey
}
func NewJwtTokenValidator(jwtVerificationKeyPath string) (JwtTokenValidator, error) {
bytes, err := ioutil.ReadFile(jwtVerificationKeyPath)
if err != nil {
return JwtTokenValidator{}, errors.WrapError(err, "Failed to read JWT Verification key")
}
verificationKey, err := jwt.ParseRSAPublicKeyFromPEM(bytes)
if err != nil {
return JwtTokenValidator{}, errors.WrapError(err, "Failed to parse RSA public key from PEM")
}
return JwtTokenValidator{verificationKey: verificationKey}, nil
}
func NewJWTTokenValidatorWithKey(verificationKey *rsa.PublicKey) JwtTokenValidator {
return JwtTokenValidator{verificationKey: verificationKey}
}
func (j JwtTokenValidator) Validate(tokenStr string) error {
token, err := jwt.Parse(tokenStr, func(t *jwt.Token) (interface{}, error) {
if !j.isValidSigningMethod(t) {
return nil, errors.Error("Invalid signing method")
}
return j.verificationKey, nil
})
if err != nil {
return errors.WrapError(err, "Validating token")
}
scopes := token.Claims.(jwt.MapClaims)["scope"].([]interface{})
for _, el := range scopes {
if el == expectedScope {
return nil
}
}
return errors.Errorf("Missing required scope: %s", expectedScope)
}
func (JwtTokenValidator) isValidSigningMethod(token *jwt.Token) bool {
switch token.Method {
case jwt.SigningMethodRS256, jwt.SigningMethodRS384, jwt.SigningMethodRS512:
return true
default:
return false
}
}