Verify verifies that a token was signed by the provided key. It unmarshals into the provided claims.
(ctx context.Context, v VerifyKeyProvider, token string, claims Claims, opts ...func(*VerifyOptions))
| 105 | |
| 106 | // Verify verifies that a token was signed by the provided key. It unmarshals into the provided claims. |
| 107 | func Verify(ctx context.Context, v VerifyKeyProvider, token string, claims Claims, opts ...func(*VerifyOptions)) error { |
| 108 | options := VerifyOptions{ |
| 109 | RegisteredClaims: jwt.Expected{ |
| 110 | Time: time.Now(), |
| 111 | }, |
| 112 | SignatureAlgorithm: SigningAlgo, |
| 113 | } |
| 114 | |
| 115 | for _, opt := range opts { |
| 116 | opt(&options) |
| 117 | } |
| 118 | |
| 119 | object, err := jose.ParseSigned(token, []jose.SignatureAlgorithm{options.SignatureAlgorithm}) |
| 120 | if err != nil { |
| 121 | return xerrors.Errorf("parse JWS: %w", err) |
| 122 | } |
| 123 | |
| 124 | if len(object.Signatures) != 1 { |
| 125 | return xerrors.New("expected 1 signature") |
| 126 | } |
| 127 | |
| 128 | signature := object.Signatures[0] |
| 129 | |
| 130 | if signature.Header.Algorithm != string(SigningAlgo) { |
| 131 | return xerrors.Errorf("expected JWS algorithm to be %q, got %q", SigningAlgo, object.Signatures[0].Header.Algorithm) |
| 132 | } |
| 133 | |
| 134 | kid := signature.Header.KeyID |
| 135 | if kid == "" { |
| 136 | return ErrMissingKeyID |
| 137 | } |
| 138 | |
| 139 | key, err := v.VerifyingKey(ctx, kid) |
| 140 | if err != nil { |
| 141 | return xerrors.Errorf("key with id %q: %w", kid, err) |
| 142 | } |
| 143 | |
| 144 | payload, err := object.Verify(key) |
| 145 | if err != nil { |
| 146 | return xerrors.Errorf("verify payload: %w", err) |
| 147 | } |
| 148 | |
| 149 | err = json.Unmarshal(payload, &claims) |
| 150 | if err != nil { |
| 151 | return xerrors.Errorf("unmarshal payload: %w", err) |
| 152 | } |
| 153 | |
| 154 | return claims.Validate(options.RegisteredClaims) |
| 155 | } |
| 156 | |
| 157 | // StaticKey fulfills the SigningKeycache and EncryptionKeycache interfaces. Useful for testing. |
| 158 | type StaticKey struct { |