| 67 | } |
| 68 | |
| 69 | func (v *TokenValidator) Validate(token string) (Identity, error) { |
| 70 | if token == "" { |
| 71 | return Identity{}, srverr.ErrNoCredentials() |
| 72 | } |
| 73 | parsed, err := jwt.Parse(token, v.keyGetter) |
| 74 | if err != nil || !parsed.Valid { |
| 75 | return Identity{}, srverr.ErrNoCredentials("invalid token") |
| 76 | } |
| 77 | if parsed.Header["alg"] != jwt.SigningMethodRS256.Alg() { |
| 78 | return Identity{}, srverr.ErrNoCredentials("invalid signing method") |
| 79 | } |
| 80 | claims := parsed.Claims.(jwt.MapClaims) |
| 81 | if !claims.VerifyAudience(v.expectedAudience, true) { |
| 82 | return Identity{}, srverr.ErrNoCredentials("invalid audience") |
| 83 | } |
| 84 | // jwt-go verifies any expiry claim, but will not fail if the expiry claim |
| 85 | // is missing. The call here with req=true ensures that the claim is both |
| 86 | // present and valid. |
| 87 | if !claims.VerifyExpiresAt(time.Now().Unix(), true) { |
| 88 | return Identity{}, srverr.ErrNoCredentials("invalid expiration") |
| 89 | } |
| 90 | if !claims.VerifyIssuer(v.expectedIssuer, true) { |
| 91 | return Identity{}, srverr.ErrNoCredentials("invalid issuer") |
| 92 | } |
| 93 | ident := Identity{AnonymousTenantID, AnonymousUserID} |
| 94 | if v, ok := claims[TenantIDClaim]; ok { |
| 95 | s, _ := v.(string) |
| 96 | if s == "" || TenantID(s) == AnonymousTenantID { |
| 97 | return Identity{}, srverr.ErrNoCredentials("invalid tenant ID") |
| 98 | } |
| 99 | ident.TenantID = TenantID(s) |
| 100 | } |
| 101 | if v, ok := claims[UserIDClaim]; ok { |
| 102 | s, _ := v.(string) |
| 103 | if s == "" || UserID(s) == AnonymousUserID { |
| 104 | return Identity{}, srverr.ErrNoCredentials("invalid tenant ID") |
| 105 | } |
| 106 | ident.UserID = UserID(s) |
| 107 | } |
| 108 | return ident, nil |
| 109 | } |
| 110 | |
| 111 | // jwks matches the format of a JSON Web Key Set file: |
| 112 | // https://auth0.com/docs/tokens/json-web-tokens/json-web-key-sets |