Decrypt decrypts the token using the provided key. It unmarshals into the provided claims.
(ctx context.Context, d DecryptKeyProvider, token string, claims Claims, opts ...func(*DecryptOptions))
| 80 | |
| 81 | // Decrypt decrypts the token using the provided key. It unmarshals into the provided claims. |
| 82 | func Decrypt(ctx context.Context, d DecryptKeyProvider, token string, claims Claims, opts ...func(*DecryptOptions)) error { |
| 83 | options := DecryptOptions{ |
| 84 | RegisteredClaims: jwt.Expected{ |
| 85 | Time: time.Now(), |
| 86 | }, |
| 87 | KeyAlgorithm: encryptKeyAlgo, |
| 88 | ContentEncryptionAlgorithm: encryptContentAlgo, |
| 89 | } |
| 90 | |
| 91 | for _, opt := range opts { |
| 92 | opt(&options) |
| 93 | } |
| 94 | |
| 95 | object, err := jose.ParseEncrypted(token, |
| 96 | []jose.KeyAlgorithm{options.KeyAlgorithm}, |
| 97 | []jose.ContentEncryption{options.ContentEncryptionAlgorithm}, |
| 98 | ) |
| 99 | if err != nil { |
| 100 | return xerrors.Errorf("parse jwe: %w", err) |
| 101 | } |
| 102 | |
| 103 | if object.Header.Algorithm != string(encryptKeyAlgo) { |
| 104 | return xerrors.Errorf("expected JWE algorithm to be %q, got %q", encryptKeyAlgo, object.Header.Algorithm) |
| 105 | } |
| 106 | |
| 107 | kid := object.Header.KeyID |
| 108 | if kid == "" { |
| 109 | return ErrMissingKeyID |
| 110 | } |
| 111 | |
| 112 | key, err := d.DecryptingKey(ctx, kid) |
| 113 | if err != nil { |
| 114 | return xerrors.Errorf("key with id %q: %w", kid, err) |
| 115 | } |
| 116 | |
| 117 | decrypted, err := object.Decrypt(key) |
| 118 | if err != nil { |
| 119 | return xerrors.Errorf("decrypt: %w", err) |
| 120 | } |
| 121 | |
| 122 | if err := json.Unmarshal(decrypted, &claims); err != nil { |
| 123 | return xerrors.Errorf("unmarshal: %w", err) |
| 124 | } |
| 125 | |
| 126 | return claims.Validate(options.RegisteredClaims) |
| 127 | } |