-
Notifications
You must be signed in to change notification settings - Fork 3
/
validator.go
56 lines (48 loc) · 1.32 KB
/
validator.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
package oidc
import (
"errors"
"github.com/golang-jwt/jwt/v4"
jwtRequest "github.com/golang-jwt/jwt/v4/request"
"net/http"
)
func NewJWTValidator(extractor jwtRequest.Extractor, provider SecretProvider, audience string, authority string) func(request *http.Request) (*jwt.Token, error) {
if extractor == nil {
extractor = jwtRequest.OAuth2Extractor
}
return func(request *http.Request) (*jwt.Token, error) {
token, err := jwtRequest.ParseFromRequest(request, extractor, func(token *jwt.Token) (i interface{}, e error) {
if id, ok := token.Header["kid"]; ok {
return provider.GetSecret(id.(string))
}
return provider.GetSecret("")
})
if err != nil {
return nil, err
}
checkAud := verifyAudience(audience, token.Claims.(jwt.MapClaims)["aud"])
if !checkAud {
return token, errors.New("invalid audience")
}
// Verify 'iss' claim
checkIss := token.Claims.(jwt.MapClaims).VerifyIssuer(authority, true)
if !checkIss {
return token, errors.New("invalid issuer")
}
return token, err
}
}
func verifyAudience(audience string, tokenAudience interface{}) bool {
switch tokenAudience.(type) {
case string:
return tokenAudience == audience
case []interface{}:
{
for _, aud := range tokenAudience.([]interface{}) {
if aud == audience {
return true
}
}
}
}
return false
}