@@ -24,6 +24,8 @@ class JWK
2424 * Parse a set of JWK keys
2525 *
2626 * @param array<mixed> $jwks The JSON Web Key Set as an associative array
27+ * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
28+ * JSON Web Key Set
2729 *
2830 * @return array<string, Key> An associative array of key IDs (kid) to Key objects
2931 *
@@ -33,7 +35,7 @@ class JWK
3335 *
3436 * @uses parseKey
3537 */
36- public static function parseKeySet (array $ jwks ): array
38+ public static function parseKeySet (array $ jwks, string $ defaultAlg = null ): array
3739 {
3840 $ keys = [];
3941
@@ -47,7 +49,7 @@ public static function parseKeySet(array $jwks): array
4749
4850 foreach ($ jwks ['keys ' ] as $ k => $ v ) {
4951 $ kid = isset ($ v ['kid ' ]) ? $ v ['kid ' ] : $ k ;
50- if ($ key = self ::parseKey ($ v )) {
52+ if ($ key = self ::parseKey ($ v, $ defaultAlg )) {
5153 $ keys [(string ) $ kid ] = $ key ;
5254 }
5355 }
@@ -63,6 +65,8 @@ public static function parseKeySet(array $jwks): array
6365 * Parse a JWK key
6466 *
6567 * @param array<mixed> $jwk An individual JWK
68+ * @param string $defaultAlg The algorithm for the Key object if "alg" is not set in the
69+ * JSON Web Key Set
6670 *
6771 * @return Key The key object for the JWK
6872 *
@@ -72,7 +76,7 @@ public static function parseKeySet(array $jwks): array
7276 *
7377 * @uses createPemFromModulusAndExponent
7478 */
75- public static function parseKey (array $ jwk ): ?Key
79+ public static function parseKey (array $ jwk, string $ defaultAlg = null ): ?Key
7680 {
7781 if (empty ($ jwk )) {
7882 throw new InvalidArgumentException ('JWK must not be empty ' );
@@ -83,10 +87,14 @@ public static function parseKey(array $jwk): ?Key
8387 }
8488
8589 if (!isset ($ jwk ['alg ' ])) {
86- // The "alg" parameter is optional in a KTY, but is required for parsing in
87- // this library. Add it manually to your JWK array if it doesn't already exist.
88- // @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
89- throw new UnexpectedValueException ('JWK must contain an "alg" parameter ' );
90+ if (\is_null ($ defaultAlg )) {
91+ // The "alg" parameter is optional in a KTY, but an algorithm is required
92+ // for parsing in this library. Use the $defaultAlg parameter when parsing the
93+ // key set in order to prevent this error.
94+ // @see https://datatracker.ietf.org/doc/html/rfc7517#section-4.4
95+ throw new UnexpectedValueException ('JWK must contain an "alg" parameter ' );
96+ }
97+ $ jwk ['alg ' ] = $ defaultAlg ;
9098 }
9199
92100 switch ($ jwk ['kty ' ]) {
0 commit comments