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

Skip to content

[Security] Access Token Authenticator #46428

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
Aug 10, 2022
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
1 change: 1 addition & 0 deletions src/Symfony/Bundle/SecurityBundle/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ CHANGELOG
* Add `Security::login()` to login programmatically
* Add `Security::logout()` to logout programmatically
* Add `security.firewalls.logout.enable_csrf` to enable CSRF protection using the default CSRF token generator
* Add RFC6750 Access Token support to allow token-based authentication

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

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <[email protected]>
*
* 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\Factory;

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

/**
* AccessTokenFactory creates services for Access Token authentication.
*
* @author Florent Morselli <[email protected]>
*
* @internal
*/
final class AccessTokenFactory extends AbstractFactory
{
private const PRIORITY = -40;

public function __construct()
{
$this->options = [];
$this->defaultFailureHandlerOptions = [];
$this->defaultSuccessHandlerOptions = [];
}

public function addConfiguration(NodeDefinition $node): void
{
$builder = $node->children();

$builder
->scalarNode('token_handler')->isRequired()->end()
->scalarNode('user_provider')->defaultNull()->end()
->scalarNode('realm')->defaultNull()->end()
->scalarNode('success_handler')->defaultNull()->end()
->scalarNode('failure_handler')->defaultNull()->end()
->arrayNode('token_extractors')
->fixXmlConfig('token_extractors')
->beforeNormalization()
->ifString()
->then(static function (string $v): array { return [$v]; })
->end()
->cannotBeEmpty()
->defaultValue([
'security.access_token_extractor.header',
])
->scalarPrototype()->end()
->end()
;
}

public function getPriority(): int
{
return self::PRIORITY;
}

/**
* {@inheritdoc}
*/
public function getKey(): string
{
return 'access_token';
}

public function createAuthenticator(ContainerBuilder $container, string $firewallName, array $config, string $userProviderId): string
{
$userProvider = new Reference($config['user_provider'] ?? $userProviderId);
$successHandler = isset($config['success_handler']) ? new Reference($this->createAuthenticationSuccessHandler($container, $firewallName, $config)) : null;
$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']);

$container
->setDefinition($authenticatorId, new ChildDefinition('security.authenticator.access_token'))
->replaceArgument(0, $userProvider)
->replaceArgument(1, new Reference($config['token_handler']))
->replaceArgument(2, new Reference($extractorId))
->replaceArgument(3, $successHandler)
->replaceArgument(4, $failureHandler)
->replaceArgument(5, $config['realm'])
;

return $authenticatorId;
}

/**
* @param array<string> $extractors
*/
private function createExtractor(ContainerBuilder $container, string $firewallName, array $extractors): string
{
$aliases = [
'query_string' => 'security.access_token_extractor.query_string',
'request_body' => 'security.access_token_extractor.request_body',
'header' => 'security.access_token_extractor.header',
];
$extractors = array_map(static function (string $extractor) use ($aliases): string {
return $aliases[$extractor] ?? $extractor;
}, $extractors);

if (1 === \count($extractors)) {
return current($extractors);
}
$extractorId = sprintf('security.authenticator.access_token.chain_extractor.%s', $firewallName);
$container
->setDefinition($extractorId, new ChildDefinition('security.authenticator.access_token.chain_extractor'))
->replaceArgument(0, array_map(function (string $extractorId): Reference {return new Reference($extractorId); }, $extractors))
;

return $extractorId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ public function load(array $configs, ContainerBuilder $container)
}

$loader->load('security_authenticator.php');
$loader->load('security_authenticator_access_token.php');

if ($container::willBeAvailable('symfony/twig-bridge', LogoutUrlExtension::class, ['symfony/security-bundle'])) {
$loader->load('templating_twig.php');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
<?php

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

namespace Symfony\Component\DependencyInjection\Loader\Configurator;

use Symfony\Component\Security\Http\AccessToken\ChainAccessTokenExtractor;
use Symfony\Component\Security\Http\AccessToken\FormEncodedBodyExtractor;
use Symfony\Component\Security\Http\AccessToken\HeaderAccessTokenExtractor;
use Symfony\Component\Security\Http\AccessToken\QueryAccessTokenExtractor;
use Symfony\Component\Security\Http\Authenticator\AccessTokenAuthenticator;

return static function (ContainerConfigurator $container) {
$container->services()
->set('security.access_token_extractor.header', HeaderAccessTokenExtractor::class)
->set('security.access_token_extractor.query_string', QueryAccessTokenExtractor::class)
->set('security.access_token_extractor.request_body', FormEncodedBodyExtractor::class)

->set('security.authenticator.access_token', AccessTokenAuthenticator::class)
->abstract()
->args([
abstract_arg('user provider'),
abstract_arg('access token handler'),
abstract_arg('access token extractor'),
null,
null,
null,
])
->call('setTranslator', [service('translator')->ignoreOnInvalid()])

->set('security.authenticator.access_token.chain_extractor', ChainAccessTokenExtractor::class)
->abstract()
->args([
abstract_arg('access token extractors'),
])
;
};
2 changes: 2 additions & 0 deletions src/Symfony/Bundle/SecurityBundle/SecurityBundle.php
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\RegisterTokenUsageTrackingPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\ReplaceDecoratedRememberMeHandlerPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Compiler\SortFirewallListenersPass;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AccessTokenFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\CustomAuthenticatorFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\FormLoginFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\FormLoginLdapFactory;
Expand Down Expand Up @@ -69,6 +70,7 @@ public function build(ContainerBuilder $container)
$extension->addAuthenticatorFactory(new CustomAuthenticatorFactory());
$extension->addAuthenticatorFactory(new LoginThrottlingFactory());
$extension->addAuthenticatorFactory(new LoginLinkFactory());
$extension->addAuthenticatorFactory(new AccessTokenFactory());

$extension->addUserProviderFactory(new InMemoryFactory());
$extension->addUserProviderFactory(new LdapFactory());
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
<?php

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

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

use PHPUnit\Framework\TestCase;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AccessTokenFactory;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\ContainerBuilder;

class AccessTokenFactoryTest extends TestCase
{
public function testBasicServiceConfiguration()
{
$container = new ContainerBuilder();
$config = [
'token_handler' => 'in_memory_token_handler_service_id',
'success_handler' => 'success_handler_service_id',
'failure_handler' => 'failure_handler_service_id',
'token_extractors' => ['BAR', 'FOO'],
];

$factory = new AccessTokenFactory();
$finalizedConfig = $this->processConfig($config, $factory);

$factory->createAuthenticator($container, 'firewall1', $finalizedConfig, 'userprovider');

$this->assertTrue($container->hasDefinition('security.authenticator.access_token.firewall1'));
}

public function testDefaultServiceConfiguration()
{
$container = new ContainerBuilder();
$config = [
'token_handler' => 'in_memory_token_handler_service_id',
];

$factory = new AccessTokenFactory();
$finalizedConfig = $this->processConfig($config, $factory);

$factory->createAuthenticator($container, 'firewall1', $finalizedConfig, 'userprovider');

$this->assertTrue($container->hasDefinition('security.authenticator.access_token.firewall1'));
}

public function testNoExtractorsDefined()
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage('The path "access_token.token_extractors" should have at least 1 element(s) defined.');
$config = [
'token_handler' => 'in_memory_token_handler_service_id',
'success_handler' => 'success_handler_service_id',
'failure_handler' => 'failure_handler_service_id',
'token_extractors' => [],
];

$factory = new AccessTokenFactory();
$this->processConfig($config, $factory);
}

public function testNoHandlerDefined()
{
$this->expectException(InvalidConfigurationException::class);
$this->expectExceptionMessage('The child config "token_handler" under "access_token" must be configured.');
$config = [
'success_handler' => 'success_handler_service_id',
'failure_handler' => 'failure_handler_service_id',
];

$factory = new AccessTokenFactory();
$this->processConfig($config, $factory);
}

private function processConfig(array $config, AccessTokenFactory $factory)
{
$nodeDefinition = new ArrayNodeDefinition('access_token');
$factory->addConfiguration($nodeDefinition);

$node = $nodeDefinition->getNode();
$normalizedConfig = $node->normalize($config);

return $node->finalize($normalizedConfig);
}
}
Loading