forked from XeroAPI/xoauth
/
validation.go
79 lines (56 loc) · 1.85 KB
/
validation.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
75
76
77
78
79
package oidc
import (
"errors"
"fmt"
"log"
"time"
"github.com/dgrijalva/jwt-go/v4"
"github.com/lestrrat-go/jwx/jwk"
)
func lookUpKey(keyId string, keys *jwk.Set) (interface{}, error) {
if key := keys.LookupKeyID(keyId); len(key) == 1 {
var rawKey interface{}
if err := key[0].Raw(&rawKey); err != nil {
return rawKey, err
}
return rawKey, nil
}
return nil, errors.New(fmt.Sprintf("unable to find key with id %s", keyId))
}
func getKeyValidatorFunc(keys *jwk.Set) func(token *jwt.Token) (interface{}, error) {
return func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodRSA); !ok {
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
}
keyId, keyOk := token.Header["kid"].(string)
if !keyOk {
return nil, errors.New("unable to parse `kid` as string")
}
var rsaPubKey, keyLookupErr = lookUpKey(keyId, keys)
if keyLookupErr != nil {
return nil, fmt.Errorf("couldn't find key with id: %s", keyId)
}
log.Printf("Using public key: %s", keyId)
return rsaPubKey, nil
}
}
func ValidateToken(tokenString string, configuration WellKnownConfiguration, clientId string) (interface{}, error) {
// Allow up to five minutes of clock skew
var clockToleranceSeconds = 300 * time.Second
keys, jwksError := jwk.FetchHTTP(configuration.JwksUri)
if jwksError != nil {
return nil, errors.New("expecting JWT header to have string kid")
}
token, tokenErr := jwt.Parse(tokenString, getKeyValidatorFunc(keys), jwt.WithLeeway(clockToleranceSeconds), jwt.WithoutAudienceValidation(), jwt.WithIssuer(configuration.Issuer))
if tokenErr != nil {
return nil, tokenErr
}
claims, ok := token.Claims.(jwt.MapClaims)
if !ok {
return nil, errors.New("failed to parse claims from JWT")
}
if !token.Valid {
return nil, errors.New("the JWT was invalid")
}
return claims, nil
}