Skip to content

Commit 6d24781

Browse files
committed
Add parsing of custom claims
1 parent 7bd8996 commit 6d24781

File tree

2 files changed

+17
-1
lines changed

2 files changed

+17
-1
lines changed

src/AuthorizationValidators/BearerTokenValidator.php

+14-1
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,8 @@ public function validateAuthorization(ServerRequestInterface $request)
118118
->withAttribute('oauth_access_token_id', $claims->get('jti'))
119119
->withAttribute('oauth_client_id', $this->convertSingleRecordAudToString($claims->get('aud')))
120120
->withAttribute('oauth_user_id', $claims->get('sub'))
121-
->withAttribute('oauth_scopes', $claims->get('scopes'));
121+
->withAttribute('oauth_scopes', $claims->get('scopes'))
122+
->withAttribute('oauth_custom_claims', $this->extractCustomClaims($claims->all()));
122123
}
123124

124125
/**
@@ -132,4 +133,16 @@ private function convertSingleRecordAudToString($aud)
132133
{
133134
return \is_array($aud) && \count($aud) === 1 ? $aud[0] : $aud;
134135
}
136+
137+
/**
138+
* Extract custom claims
139+
*
140+
* @param array $claims
141+
*
142+
* @return array
143+
*/
144+
private function extractCustomClaims($claims)
145+
{
146+
return \array_diff_key($claims, \array_flip(['jti', 'aud', 'sub', 'scopes', 'iat', 'nbf', 'exp']));
147+
}
135148
}

tests/AuthorizationValidators/BearerTokenValidatorTest.php

+3
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ public function testBearerTokenValidatorAcceptsValidToken()
3434
->expiresAt((new DateTimeImmutable())->add(new DateInterval('PT1H')))
3535
->relatedTo('user-id')
3636
->withClaim('scopes', 'scope1 scope2 scope3 scope4')
37+
->withClaim('attr1', 'value')
38+
->withClaim('attr2', 42)
3739
->getToken(new Sha256(), LocalFileReference::file(__DIR__ . '/../Stubs/private.key'));
3840

3941
$request = (new ServerRequest())->withHeader('authorization', \sprintf('Bearer %s', $validJwt->toString()));
@@ -46,6 +48,7 @@ public function testBearerTokenValidatorAcceptsValidToken()
4648
$this->assertEquals('client-id', $validRequest->getAttribute('oauth_client_id'));
4749
$this->assertEquals('user-id', $validRequest->getAttribute('oauth_user_id'));
4850
$this->assertEquals('scope1 scope2 scope3 scope4', $validRequest->getAttribute('oauth_scopes'));
51+
$this->assertEquals(['attr1' => 'value', 'attr2' => 42], $validRequest->getAttribute('oauth_custom_claims'));
4952
}
5053

5154
public function testBearerTokenValidatorRejectsExpiredToken()

0 commit comments

Comments
 (0)