File tree Expand file tree Collapse file tree 2 files changed +27
-4
lines changed Expand file tree Collapse file tree 2 files changed +27
-4
lines changed Original file line number Diff line number Diff line change @@ -203,13 +203,14 @@ public static function encode(
203203 string $ keyId = null ,
204204 array $ head = null
205205 ): string {
206- $ header = ['typ ' => 'JWT ' , 'alg ' => $ alg ];
206+ $ header = ['typ ' => 'JWT ' ];
207+ if (isset ($ head ) && \is_array ($ head )) {
208+ $ header = \array_merge ($ header , $ head );
209+ }
210+ $ header ['alg ' ] = $ alg ;
207211 if ($ keyId !== null ) {
208212 $ header ['kid ' ] = $ keyId ;
209213 }
210- if (isset ($ head ) && \is_array ($ head )) {
211- $ header = \array_merge ($ head , $ header );
212- }
213214 $ segments = [];
214215 $ segments [] = static ::urlsafeB64Encode ((string ) static ::jsonEncode ($ header ));
215216 $ segments [] = static ::urlsafeB64Encode ((string ) static ::jsonEncode ($ payload ));
Original file line number Diff line number Diff line change @@ -518,4 +518,26 @@ public function testGetHeaders()
518518 $ this ->assertEquals ($ headers ->typ , 'JWT ' );
519519 $ this ->assertEquals ($ headers ->alg , 'HS256 ' );
520520 }
521+
522+ public function testAdditionalHeaderOverrides ()
523+ {
524+ $ msg = JWT ::encode (
525+ ['message ' => 'abc ' ],
526+ 'my_key ' ,
527+ 'HS256 ' ,
528+ 'my_key_id ' ,
529+ [
530+ 'cty ' => 'test-eit;v=1 ' ,
531+ 'typ ' => 'JOSE ' , // override type header
532+ 'kid ' => 'not_my_key_id ' , // should not override $key param
533+ 'alg ' => 'BAD ' , // should not override $alg param
534+ ]
535+ );
536+ $ headers = new stdClass ();
537+ JWT ::decode ($ msg , new Key ('my_key ' , 'HS256 ' ), $ headers );
538+ $ this ->assertEquals ('test-eit;v=1 ' , $ headers ->cty , 'additional field works ' );
539+ $ this ->assertEquals ('JOSE ' , $ headers ->typ , 'typ override works ' );
540+ $ this ->assertEquals ('my_key_id ' , $ headers ->kid , 'key param not overridden ' );
541+ $ this ->assertEquals ('HS256 ' , $ headers ->alg , 'alg param not overridden ' );
542+ }
521543}
You can’t perform that action at this time.
0 commit comments