Skip to content

Commit

Permalink
Add parsing of custom claims
Browse files Browse the repository at this point in the history
  • Loading branch information
ElisDN committed May 4, 2021
1 parent 7bd8996 commit 6d24781
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/AuthorizationValidators/BearerTokenValidator.php
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,8 @@ public function validateAuthorization(ServerRequestInterface $request)
->withAttribute('oauth_access_token_id', $claims->get('jti'))
->withAttribute('oauth_client_id', $this->convertSingleRecordAudToString($claims->get('aud')))
->withAttribute('oauth_user_id', $claims->get('sub'))
->withAttribute('oauth_scopes', $claims->get('scopes'));
->withAttribute('oauth_scopes', $claims->get('scopes'))
->withAttribute('oauth_custom_claims', $this->extractCustomClaims($claims->all()));
}

/**
Expand All @@ -132,4 +133,16 @@ private function convertSingleRecordAudToString($aud)
{
return \is_array($aud) && \count($aud) === 1 ? $aud[0] : $aud;
}

/**
* Extract custom claims
*
* @param array $claims
*
* @return array
*/
private function extractCustomClaims($claims)
{
return \array_diff_key($claims, \array_flip(['jti', 'aud', 'sub', 'scopes', 'iat', 'nbf', 'exp']));
}
}
3 changes: 3 additions & 0 deletions tests/AuthorizationValidators/BearerTokenValidatorTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ public function testBearerTokenValidatorAcceptsValidToken()
->expiresAt((new DateTimeImmutable())->add(new DateInterval('PT1H')))
->relatedTo('user-id')
->withClaim('scopes', 'scope1 scope2 scope3 scope4')
->withClaim('attr1', 'value')
->withClaim('attr2', 42)
->getToken(new Sha256(), LocalFileReference::file(__DIR__ . '/../Stubs/private.key'));

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

public function testBearerTokenValidatorRejectsExpiredToken()
Expand Down

0 comments on commit 6d24781

Please sign in to comment.