Skip to content

[Security] Add OidcUserInfoTokenHandler and OidcUser #48272

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

Merged
merged 1 commit into from
Apr 14, 2023
Merged
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
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -150,9 +150,12 @@
"symfony/phpunit-bridge": "^5.4|^6.0",
"symfony/runtime": "self.version",
"symfony/security-acl": "~2.8|~3.0",
"symfony/string": "^5.4|^6.0",
"twig/cssinliner-extra": "^2.12|^3",
"twig/inky-extra": "^2.12|^3",
"twig/markdown-extra": "^2.12|^3"
"twig/markdown-extra": "^2.12|^3",
"web-token/jwt-checker": "^3.1",
"web-token/jwt-signature-algorithm-ecdsa": "^3.1"
},
"conflict": {
"ext-psr": "<1.1|>=2",
Expand Down
1 change: 1 addition & 0 deletions src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ CHANGELOG
* Make `Security::login()` return the authenticator response
* Deprecate the `security.firewalls.logout.csrf_token_generator` config option, use `security.firewalls.logout.csrf_token_manager` instead
* Make firewalls event dispatcher traceable on debug mode
* Add `TokenHandlerFactoryInterface`, `OidcUserInfoTokenHandlerFactory`, `OidcTokenHandlerFactory` and `ServiceTokenHandlerFactory` for `AccessTokenFactory`

6.2
---
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\AccessToken;

use Jose\Component\Core\Algorithm;
use Jose\Component\Core\JWK;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SignatureAlgorithmFactory;
use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

/**
* Configures a token handler for decoding and validating an OIDC token.
*
* @experimental
*/
class OidcTokenHandlerFactory implements TokenHandlerFactoryInterface
{
public function create(ContainerBuilder $container, string $id, array|string $config): void
{
$tokenHandlerDefinition = $container->setDefinition($id, new ChildDefinition('security.access_token_handler.oidc'));
$tokenHandlerDefinition->replaceArgument(3, $config['claim']);
$tokenHandlerDefinition->replaceArgument(4, $config['audience']);

// Create the signature algorithm and the JWK
if (!ContainerBuilder::willBeAvailable('web-token/jwt-core', Algorithm::class, ['symfony/security-bundle'])) {
$container->register('security.access_token_handler.oidc.signature', 'stdClass')
->addError('You cannot use the "oidc" token handler since "web-token/jwt-core" is not installed. Try running "web-token/jwt-core".');
$container->register('security.access_token_handler.oidc.jwk', 'stdClass')
->addError('You cannot use the "oidc" token handler since "web-token/jwt-core" is not installed. Try running "web-token/jwt-core".');
} else {
$container->register('security.access_token_handler.oidc.signature', Algorithm::class)
->setFactory([SignatureAlgorithmFactory::class, 'create'])
->setArguments([$config['signature']['algorithm']]);
$container->register('security.access_token_handler.oidc.jwk', JWK::class)
->setFactory([JWK::class, 'createFromJson'])
->setArguments([$config['signature']['key']]);
}
$tokenHandlerDefinition->replaceArgument(0, new Reference('security.access_token_handler.oidc.signature'));
$tokenHandlerDefinition->replaceArgument(1, new Reference('security.access_token_handler.oidc.jwk'));
}

public function getKey(): string
{
return 'oidc';
}

public function addConfiguration(NodeBuilder $node): void
{
$node
->arrayNode($this->getKey())
->fixXmlConfig($this->getKey())
->children()
->scalarNode('claim')
->info('Claim which contains the user identifier (e.g.: sub, email..).')
->defaultValue('sub')
->end()
->scalarNode('audience')
->info('Audience set in the token, for validation purpose.')
->defaultNull()
->end()
->arrayNode('signature')
->isRequired()
->children()
->scalarNode('algorithm')
->info('Algorithm used to sign the token.')
->isRequired()
->end()
->scalarNode('key')
->info('JSON-encoded JWK used to sign the token (must contain a "kty" key).')
->isRequired()
->end()
->end()
->end()
->end()
->end()
;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\AccessToken;

use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\HttpClient\HttpClient;

/**
* Configures a token handler for an OIDC server.
*
* @experimental
*/
class OidcUserInfoTokenHandlerFactory implements TokenHandlerFactoryInterface
{
public function create(ContainerBuilder $container, string $id, array|string $config): void
{
$tokenHandlerDefinition = $container->setDefinition($id, new ChildDefinition('security.access_token_handler.oidc_user_info'));
$tokenHandlerDefinition->replaceArgument(2, $config['claim']);

// Create the client service
if (!isset($config['client']['id'])) {
$clientDefinitionId = 'http_client.security.access_token_handler.oidc_user_info';
if (!ContainerBuilder::willBeAvailable('symfony/http-client', HttpClient::class, ['symfony/security-bundle'])) {
$container->register($clientDefinitionId, 'stdClass')
->addError('You cannot use the "oidc_user_info" token handler since the HttpClient component is not installed. Try running "composer require symfony/http-client".');
} else {
$container->register($clientDefinitionId, HttpClient::class)
->setFactory([HttpClient::class, 'create'])
->setArguments([$config['client']])
->addTag('http_client.client');
}
}

$tokenHandlerDefinition->replaceArgument(0, new Reference($config['client']['id'] ?? $clientDefinitionId));
}

public function getKey(): string
{
return 'oidc_user_info';
}

public function addConfiguration(NodeBuilder $node): void
{
$node
->arrayNode($this->getKey())
->fixXmlConfig($this->getKey())
->children()
->scalarNode('claim')
->info('Claim which contains the user identifier (e.g.: sub, email..).')
->defaultValue('sub')
->end()
->arrayNode('client')
->info('HttpClient to call the OIDC server.')
->isRequired()
->beforeNormalization()
->ifString()
->then(static function ($v): array { return ['id' => $v]; })
->end()
->prototype('scalar')->end()
->end()
->end()
->end()
;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\AccessToken;

use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* Configures a token handler from a service id.
*
* @see \Symfony\Bundle\SecurityBundle\Tests\DependencyInjection\Security\Factory\AccessTokenFactoryTest
*
* @experimental
*/
class ServiceTokenHandlerFactory implements TokenHandlerFactoryInterface
{
public function create(ContainerBuilder $container, string $id, array|string $config): void
{
$container->setDefinition($id, new ChildDefinition($config));
}

public function getKey(): string
{
return 'id';
}

public function addConfiguration(NodeBuilder $node): void
{
$node->scalarNode($this->getKey())->end();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien@symfony.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\AccessToken;

use Symfony\Component\Config\Definition\Builder\NodeBuilder;
use Symfony\Component\DependencyInjection\ContainerBuilder;

/**
* Allows creating configurable token handlers.
*
* @experimental
*/
interface TokenHandlerFactoryInterface
{
/**
* Creates a generic token handler service.
*/
public function create(ContainerBuilder $container, string $id, array|string $config): void;

/**
* Gets a generic token handler configuration key.
*/
public function getKey(): string;

/**
* Adds a generic token handler configuration.
*/
public function addConfiguration(NodeBuilder $node): void;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,9 @@

namespace Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory;

use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\AccessToken\TokenHandlerFactoryInterface;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
Expand All @@ -27,7 +29,10 @@ final class AccessTokenFactory extends AbstractFactory implements StatelessAuthe
{
private const PRIORITY = -40;

public function __construct()
/**
* @param array<array-key, TokenHandlerFactoryInterface> $tokenHandlerFactories
*/
public function __construct(private readonly array $tokenHandlerFactories)
{
$this->options = [];
$this->defaultFailureHandlerOptions = [];
Expand All @@ -40,7 +45,6 @@ public function addConfiguration(NodeDefinition $node): void

$builder = $node->children();
$builder
->scalarNode('token_handler')->isRequired()->end()
->scalarNode('realm')->defaultNull()->end()
->arrayNode('token_extractors')
->fixXmlConfig('token_extractors')
Expand All @@ -55,6 +59,38 @@ public function addConfiguration(NodeDefinition $node): void
->scalarPrototype()->end()
->end()
;

$tokenHandlerNodeBuilder = $builder
->arrayNode('token_handler')
->example([
'id' => 'App\Security\CustomTokenHandler',
])

->beforeNormalization()
->ifString()
->then(static function (string $v): array { return ['id' => $v]; })
->end()

->beforeNormalization()
->ifTrue(static function ($v) { return \is_array($v) && 1 < \count($v); })
->then(static function () { throw new InvalidConfigurationException('You cannot configure multiple token handlers.'); })
->end()

// "isRequired" must be set otherwise the following custom validation is not called
->isRequired()
->beforeNormalization()
->ifTrue(static function ($v) { return \is_array($v) && !$v; })
->then(static function () { throw new InvalidConfigurationException('You must set a token handler.'); })
->end()

->children()
;

foreach ($this->tokenHandlerFactories as $factory) {
$factory->addConfiguration($tokenHandlerNodeBuilder);
}

$tokenHandlerNodeBuilder->end();
}

public function getPriority(): int
Expand All @@ -73,10 +109,11 @@ public function createAuthenticator(ContainerBuilder $container, string $firewal
$failureHandler = isset($config['failure_handler']) ? new Reference($this->createAuthenticationFailureHandler($container, $firewallName, $config)) : null;
$authenticatorId = sprintf('security.authenticator.access_token.%s', $firewallName);
$extractorId = $this->createExtractor($container, $firewallName, $config['token_extractors']);
$tokenHandlerId = $this->createTokenHandler($container, $firewallName, $config['token_handler'], $userProviderId);

$container
->setDefinition($authenticatorId, new ChildDefinition('security.authenticator.access_token'))
->replaceArgument(0, new Reference($config['token_handler']))
->replaceArgument(0, new Reference($tokenHandlerId))
->replaceArgument(1, new Reference($extractorId))
->replaceArgument(2, $userProviderId ? new Reference($userProviderId) : null)
->replaceArgument(3, $successHandler)
Expand Down Expand Up @@ -110,4 +147,20 @@ private function createExtractor(ContainerBuilder $container, string $firewallNa

return $extractorId;
}

private function createTokenHandler(ContainerBuilder $container, string $firewallName, array $config, ?string $userProviderId): string
{
$key = array_keys($config)[0];
$id = sprintf('security.access_token_handler.%s', $firewallName);

foreach ($this->tokenHandlerFactories as $factory) {
if ($key !== $factory->getKey()) {
continue;
}

$factory->create($container, $id, $config[$key], $userProviderId);
}

return $id;
}
}
Loading
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy