Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[Security] OidcTokenHandler support JWKSet #51665

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,21 @@ public function create(ContainerBuilder $container, string $id, array|string $co
// @see Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SignatureAlgorithmFactory
// for supported algorithms
if (\in_array($config['algorithm'], ['ES256', 'ES384', 'ES512'], true)) {
$tokenHandlerDefinition->replaceArgument(0, new Reference('security.access_token_handler.oidc.signature.'.$config['algorithm']));
$algorithmDefinition = new Reference('security.access_token_handler.oidc.signature.'.$config['algorithm']);
} else {
$tokenHandlerDefinition->replaceArgument(0, (new ChildDefinition('security.access_token_handler.oidc.signature'))
$algorithmDefinition = (new ChildDefinition('security.access_token_handler.oidc.signature'))
->replaceArgument(0, $config['algorithm'])
);
;
}

$algorithmManagerDefinition = $container->setDefinition($id.'.algorithm_manager', (new ChildDefinition('security.access_token_handler.oidc.algorithm_manager'))
->replaceArgument(0, [$algorithmDefinition])
);

$tokenHandlerDefinition->replaceArgument(0, $algorithmManagerDefinition);

if (!isset($config['key'])) {
throw new LogicException('You should defined key parameter in configuration.');
}

$tokenHandlerDefinition->replaceArgument(1, (new ChildDefinition('security.access_token_handler.oidc.jwk'))
Expand Down Expand Up @@ -80,7 +90,6 @@ public function addConfiguration(NodeBuilder $node): void
->end()
->scalarNode('key')
->info('JSON-encoded JWK used to sign the token (must contain a "kty" key).')
->isRequired()
->end()
->end()
->end()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Jose\Component\Core\Algorithm;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\Algorithm\ES384;
Expand Down Expand Up @@ -89,6 +90,12 @@
abstract_arg('signature algorithm'),
])

->set('security.access_token_handler.oidc.algorithm_manager', AlgorithmManager::class)
->abstract()
->args([
abstract_arg('signature algorithms'),
])

->set('security.access_token_handler.oidc.signature.ES256', ES256::class)
->parent('security.access_token_handler.oidc.signature')
->args(['index_0' => 'ES256'])
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Jose\Component\Core\Algorithm;
use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\JWKSet;
use Jose\Component\Signature\JWSTokenSupport;
use Jose\Component\Signature\JWSVerifier;
use Jose\Component\Signature\Serializer\CompactSerializer;
Expand All @@ -37,15 +38,23 @@ final class OidcTokenHandler implements AccessTokenHandlerInterface
{
use OidcTrait;

private AlgorithmManager $algorithmManager;

public function __construct(
private Algorithm $signatureAlgorithm,
private JWK $jwk,
private Algorithm|AlgorithmManager $signatureAlgorithm,
private JWK|JWKSet $jwk,
private string $audience,
private array $issuers,
private string $claim = 'sub',
private ?LoggerInterface $logger = null,
private ClockInterface $clock = new Clock(),
) {
if ($this->signatureAlgorithm instanceof Algorithm) {
trigger_deprecation('symfony/security-http', '7.1', 'First argument must be instance of %s, %s given.', AlgorithmManager::class, Algorithm::class);
$this->algorithmManager = new AlgorithmManager([$this->signatureAlgorithm]);
} else {
$this->algorithmManager = $signatureAlgorithm;
}
}

public function getUserBadgeFrom(string $accessToken): UserBadge
Expand All @@ -56,19 +65,27 @@ public function getUserBadgeFrom(string $accessToken): UserBadge

try {
// Decode the token
$jwsVerifier = new JWSVerifier(new AlgorithmManager([$this->signatureAlgorithm]));
$jwsVerifier = new JWSVerifier($this->algorithmManager);
$serializerManager = new JWSSerializerManager([new CompactSerializer()]);
$jws = $serializerManager->unserialize($accessToken);
$claims = json_decode($jws->getPayload(), true);

// Verify the signature
if (!$jwsVerifier->verifyWithKey($jws, $this->jwk, 0)) {
if ($this->jwk instanceof JWK) {
if (!$jwsVerifier->verifyWithKey($jws, $this->jwk, 0)) {
throw new InvalidSignatureException();
}
} elseif ($this->jwk instanceof JWKSet) {
if (!$jwsVerifier->verifyWithKeySet($jws, $this->jwk, 0)) {
throw new InvalidSignatureException();
}
} else {
throw new InvalidSignatureException();
}

// Verify the headers
$headerCheckerManager = new Checker\HeaderCheckerManager([
new Checker\AlgorithmChecker([$this->signatureAlgorithm->name()]),
new Checker\AlgorithmChecker($this->algorithmManager->list()),
], [
new JWSTokenSupport(),
]);
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/Http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ CHANGELOG
---

* Add `#[IsCsrfTokenValid]` attribute
* Deprecate passing a Algorithm object as the 1st argument to the constructor of `Symfony\Component\Security\Http\AccessToken\Oidc\OidcTokenHandler`

7.0
---
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@

use Jose\Component\Core\AlgorithmManager;
use Jose\Component\Core\JWK;
use Jose\Component\Core\JWKSet;
use Jose\Component\Signature\Algorithm\ES256;
use Jose\Component\Signature\JWSBuilder;
use Jose\Component\Signature\Serializer\CompactSerializer;
Expand All @@ -32,9 +33,9 @@ class OidcTokenHandlerTest extends TestCase
private const AUDIENCE = 'Symfony OIDC';

/**
* @dataProvider getClaims
* @dataProvider getClaimsAndJwk
*/
public function testGetsUserIdentifierFromSignedToken(string $claim, string $expected)
public function testGetsUserIdentifierFromSignedToken(string $claim, string $expected, JWK|JWKSet $jwk)
{
$time = time();
$claims = [
Expand All @@ -53,8 +54,8 @@ public function testGetsUserIdentifierFromSignedToken(string $claim, string $exp
$loggerMock->expects($this->never())->method('error');

$userBadge = (new OidcTokenHandler(
new ES256(),
$this->getJWK(),
new AlgorithmManager([new ES256()]),
$jwk,
self::AUDIENCE,
['https://www.example.com'],
$claim,
Expand All @@ -69,10 +70,12 @@ public function testGetsUserIdentifierFromSignedToken(string $claim, string $exp
$this->assertEquals($claims['sub'], $actualUser->getUserIdentifier());
}

public static function getClaims(): iterable
public static function getClaimsAndJwk(): iterable
{
yield ['sub', 'e21bf182-1538-406e-8ccb-e25a17aba39f'];
yield ['email', '[email protected]'];
yield ['sub', 'e21bf182-1538-406e-8ccb-e25a17aba39f', self::getJWK()];
yield ['email', '[email protected]', self::getJWK()];
yield ['sub', 'e21bf182-1538-406e-8ccb-e25a17aba39f', self::getJWKSet()];
yield ['email', '[email protected]', self::getJWKSet()];
}

/**
Expand All @@ -87,7 +90,7 @@ public function testThrowsAnErrorIfTokenIsInvalid(string $token)
$this->expectExceptionMessage('Invalid credentials.');

(new OidcTokenHandler(
new ES256(),
new AlgorithmManager([new ES256()]),
$this->getJWK(),
self::AUDIENCE,
['https://www.example.com'],
Expand Down Expand Up @@ -146,7 +149,7 @@ public function testThrowsAnErrorIfUserPropertyIsMissing()
$this->expectExceptionMessage('Invalid credentials.');

(new OidcTokenHandler(
new ES256(),
new AlgorithmManager([new ES256()]),
self::getJWK(),
self::AUDIENCE,
['https://www.example.com'],
Expand Down Expand Up @@ -177,4 +180,16 @@ private static function getJWK(): JWK
'd' => 'iA_TV2zvftni_9aFAQwFO_9aypfJFCSpcCyevDvz220',
]);
}

private static function getJWKSet(): JWKSet
{
// tip: use https://mkjwk.org/ to generate a JWK
return new JWKSet([new JWK([
'kty' => 'EC',
'crv' => 'P-256',
'x' => '0QEAsI1wGI-dmYatdUZoWSRWggLEpyzopuhwk-YUnA4',
'y' => 'KYl-qyZ26HobuYwlQh-r0iHX61thfP82qqEku7i0woo',
'd' => 'iA_TV2zvftni_9aFAQwFO_9aypfJFCSpcCyevDvz220',
])]);
}
}
1 change: 1 addition & 0 deletions src/Symfony/Component/Security/Http/composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
],
"require": {
"php": ">=8.2",
"symfony/deprecation-contracts": "^2.5|^3",
"symfony/http-foundation": "^6.4|^7.0",
"symfony/http-kernel": "^6.4|^7.0",
"symfony/polyfill-mbstring": "~1.0",
Expand Down