From fd3fd96f753f24c7bfafa7f0255252427fec7f61 Mon Sep 17 00:00:00 2001 From: Vitor Esposito Date: Tue, 28 Jan 2025 11:58:52 -0300 Subject: [PATCH] Custom payload in jwt --- src/JwtManager.php | 13 ++++++++++--- tests/JwtManagerTest.php | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+), 3 deletions(-) diff --git a/src/JwtManager.php b/src/JwtManager.php index 5f7b1d0..f6d9a4d 100755 --- a/src/JwtManager.php +++ b/src/JwtManager.php @@ -52,11 +52,13 @@ private function getHeader(): string * mount and get the payload part * @param string $audience * @param string $subject + * @param array $customPayload * @return string */ private function getPayload( string $audience, - string $subject + string $subject, + array $customPayload ): string { $payload = [ 'aud' => $audience, @@ -65,7 +67,10 @@ private function getPayload( 'iss' => $this->context, 'sub' => $subject, ]; + + $payload = array_merge($customPayload, $payload); $payload = json_encode($payload); + return $this->base64UrlEncode($payload); } @@ -117,14 +122,16 @@ public function getexpire(): int * generate token * @param string $audience * @param string $subject + * @param array $payload * @return string */ public function generate( string $audience, - string $subject = '' + string $subject = '', + array $customPayload = [] ): string { $header = $this->getHeader(); - $payload = $this->getPayload($audience, $subject); + $payload = $this->getPayload($audience, $subject, $customPayload); $signature = $this->getSignature($header, $payload); return $header . '.' . $payload . '.' . $signature; diff --git a/tests/JwtManagerTest.php b/tests/JwtManagerTest.php index 7c54099..4696632 100755 --- a/tests/JwtManagerTest.php +++ b/tests/JwtManagerTest.php @@ -272,6 +272,38 @@ public function testTokenNotNeedToRefresh() $this->assertFalse($need); } + /** + * @covers JwtManager\JwtManager::isValid + * @covers JwtManager\JwtManager::splitParts + * @covers JwtManager\JwtManager::getSignature + * @covers JwtManager\JwtManager::base64UrlEncode + */ + public function testCustomPayload() + { + $JwtManager = new JwtManager( + $this->appSecret, + $this->context + ); + + $token = $JwtManager->generate( + 'token', + '68162dc1-a392-491f-9d46-639f0e0f179d0', + [ + 'test' => 'test', + ] + ); + + $JwtManager = new JwtManager( + $this->appSecret, + $this->context + ); + + $payload = $JwtManager->decodePayload($token); + + $this->assertIsArray($payload); + $this->assertEquals($payload['test'], 'test'); + } + protected function tearDown(): void { //