remove simple_preauth and simple_form authenticators

This commit is contained in:
Christian Flothmann 2019-05-30 11:39:41 +02:00
parent dc82bba1e1
commit 35de7e2545
21 changed files with 7 additions and 1265 deletions

View File

@ -5,6 +5,10 @@ CHANGELOG
-----
* Removed the ability to configure encoders using `argon2i` or `bcrypt` as algorithm, use `auto` instead
* The `simple_form` and `simple_preauth` authentication listeners have been removed,
use Guard instead.
* The `SimpleFormFactory` and `SimplePreAuthenticationFactory` classes have been removed,
use Guard instead.
4.3.0
-----

View File

@ -12,8 +12,6 @@
namespace Symfony\Bundle\SecurityBundle\DependencyInjection;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\AbstractFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimpleFormFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimplePreAuthenticationFactory;
use Symfony\Component\Config\Definition\Builder\ArrayNodeDefinition;
use Symfony\Component\Config\Definition\Builder\TreeBuilder;
use Symfony\Component\Config\Definition\ConfigurationInterface;
@ -292,10 +290,6 @@ class MainConfiguration implements ConfigurationInterface
->canBeUnset()
;
if ($factory instanceof SimplePreAuthenticationFactory || $factory instanceof SimpleFormFactory) {
$factoryNode->setDeprecated(sprintf('The "%s" security listener is deprecated Symfony 4.2, use Guard instead.', $name));
}
if ($factory instanceof AbstractFactory) {
$abstractFactoryKeys[] = $name;
}

View File

@ -1,87 +0,0 @@
<?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\Factory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
class SimpleFormFactory extends FormLoginFactory
{
public function __construct(bool $triggerDeprecation = true)
{
parent::__construct();
$this->addOption('authenticator', null);
if ($triggerDeprecation) {
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', __CLASS__), E_USER_DEPRECATED);
}
}
public function getKey()
{
return 'simple-form';
}
public function addConfiguration(NodeDefinition $node)
{
parent::addConfiguration($node);
$node->children()
->scalarNode('authenticator')->cannotBeEmpty()->end()
->end();
}
protected function getListenerId()
{
return 'security.authentication.listener.simple_form';
}
protected function createAuthProvider(ContainerBuilder $container, $id, $config, $userProviderId)
{
$provider = 'security.authentication.provider.simple_form.'.$id;
$container
->setDefinition($provider, new ChildDefinition('security.authentication.provider.simple'))
->replaceArgument(0, new Reference($config['authenticator']))
->replaceArgument(1, new Reference($userProviderId))
->replaceArgument(2, $id)
->replaceArgument(3, new Reference('security.user_checker.'.$id))
;
return $provider;
}
protected function createListener($container, $id, $config, $userProvider)
{
$listenerId = parent::createListener($container, $id, $config, $userProvider);
$simpleAuthHandlerId = 'security.authentication.simple_success_failure_handler.'.$id;
$simpleAuthHandler = $container->setDefinition($simpleAuthHandlerId, new ChildDefinition('security.authentication.simple_success_failure_handler'));
$simpleAuthHandler->replaceArgument(0, new Reference($config['authenticator']));
$simpleAuthHandler->replaceArgument(1, new Reference($this->getSuccessHandlerId($id)));
$simpleAuthHandler->replaceArgument(2, new Reference($this->getFailureHandlerId($id)));
$listener = $container->getDefinition($listenerId);
$listener->replaceArgument(5, new Reference($simpleAuthHandlerId));
$listener->replaceArgument(6, new Reference($simpleAuthHandlerId));
$listener->addArgument(new Reference($config['authenticator']));
return $listenerId;
}
}

View File

@ -1,73 +0,0 @@
<?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\Factory;
use Symfony\Component\Config\Definition\Builder\NodeDefinition;
use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
class SimplePreAuthenticationFactory implements SecurityFactoryInterface
{
public function __construct(bool $triggerDeprecation = true)
{
if ($triggerDeprecation) {
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', __CLASS__), E_USER_DEPRECATED);
}
}
public function getPosition()
{
return 'pre_auth';
}
public function getKey()
{
return 'simple-preauth';
}
public function addConfiguration(NodeDefinition $node)
{
$node
->children()
->scalarNode('provider')->end()
->scalarNode('authenticator')->cannotBeEmpty()->end()
->end()
;
}
public function create(ContainerBuilder $container, $id, $config, $userProvider, $defaultEntryPoint)
{
$provider = 'security.authentication.provider.simple_preauth.'.$id;
$container
->setDefinition($provider, new ChildDefinition('security.authentication.provider.simple'))
->replaceArgument(0, new Reference($config['authenticator']))
->replaceArgument(1, new Reference($userProvider))
->replaceArgument(2, $id)
->replaceArgument(3, new Reference('security.user_checker.'.$id))
;
// listener
$listenerId = 'security.authentication.listener.simple_preauth.'.$id;
$listener = $container->setDefinition($listenerId, new ChildDefinition('security.authentication.listener.simple_preauth'));
$listener->replaceArgument(2, $id);
$listener->replaceArgument(3, new Reference($config['authenticator']));
$listener->addMethodCall('setSessionAuthenticationStrategy', [new Reference('security.authentication.session_strategy.'.$id)]);
return [$provider, $listenerId, null];
}
}

View File

@ -109,35 +109,6 @@
public="false"
abstract="true" />
<service id="security.authentication.listener.simple_form"
class="Symfony\Component\Security\Http\Firewall\SimpleFormAuthenticationListener"
parent="security.authentication.listener.abstract"
public="false"
abstract="true">
<deprecated>The "%service_id%" service is deprecated since Symfony 4.2.</deprecated>
</service>
<service id="security.authentication.simple_success_failure_handler" class="Symfony\Component\Security\Http\Authentication\SimpleAuthenticationHandler" abstract="true">
<tag name="monolog.logger" channel="security" />
<argument /> <!-- Authenticator -->
<argument type="service" id="security.authentication.success_handler" />
<argument type="service" id="security.authentication.failure_handler" />
<argument type="service" id="logger" on-invalid="null" />
<deprecated>The "%service_id%" service is deprecated since Symfony 4.2.</deprecated>
</service>
<service id="security.authentication.listener.simple_preauth" class="Symfony\Component\Security\Http\Firewall\SimplePreAuthenticationListener" abstract="true">
<tag name="monolog.logger" channel="security" />
<argument type="service" id="security.token_storage" />
<argument type="service" id="security.authentication.manager" />
<argument /> <!-- Provider-shared Key -->
<argument /> <!-- Authenticator -->
<argument type="service" id="logger" on-invalid="null" />
<argument type="service" id="event_dispatcher" on-invalid="null"/>
<argument type="service" id="security.authentication.trust_resolver" />
<deprecated>The "%service_id%" service is deprecated since Symfony 4.2.</deprecated>
</service>
<service id="security.authentication.listener.x509" class="Symfony\Component\Security\Http\Firewall\X509AuthenticationListener" abstract="true">
<tag name="monolog.logger" channel="security" />
<argument type="service" id="security.token_storage" />
@ -199,14 +170,6 @@
<argument>%security.authentication.hide_user_not_found%</argument>
</service>
<service id="security.authentication.provider.simple" class="Symfony\Component\Security\Core\Authentication\Provider\SimpleAuthenticationProvider" abstract="true">
<argument /> <!-- Simple Authenticator -->
<argument /> <!-- User Provider -->
<argument /> <!-- Provider-shared Key -->
<argument>null</argument> <!-- UserChecker -->
<deprecated>The "%service_id%" service is deprecated since Symfony 4.2.</deprecated>
</service>
<service id="security.authentication.provider.pre_authenticated" class="Symfony\Component\Security\Core\Authentication\Provider\PreAuthenticatedAuthenticationProvider" abstract="true">
<argument /> <!-- User Provider -->
<argument /> <!-- User Checker -->

View File

@ -24,8 +24,6 @@ use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\JsonLogin
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\JsonLoginLdapFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RememberMeFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\RemoteUserFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimpleFormFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\SimplePreAuthenticationFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\Factory\X509Factory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\InMemoryFactory;
use Symfony\Bundle\SecurityBundle\DependencyInjection\Security\UserProvider\LdapFactory;
@ -54,8 +52,6 @@ class SecurityBundle extends Bundle
$extension->addSecurityListenerFactory(new RememberMeFactory());
$extension->addSecurityListenerFactory(new X509Factory());
$extension->addSecurityListenerFactory(new RemoteUserFactory());
$extension->addSecurityListenerFactory(new SimplePreAuthenticationFactory(false));
$extension->addSecurityListenerFactory(new SimpleFormFactory(false));
$extension->addSecurityListenerFactory(new GuardAuthenticationFactory());
$extension->addUserProviderFactory(new InMemoryFactory());

View File

@ -474,50 +474,6 @@ abstract class CompleteConfigurationTest extends TestCase
$this->addToAssertionCount(1);
}
/**
* @group legacy
* @expectedDeprecation The "simple_form" security listener is deprecated Symfony 4.2, use Guard instead.
*/
public function testSimpleAuth()
{
$container = $this->getContainer('simple_auth');
$arguments = $container->getDefinition('security.firewall.map')->getArguments();
$listeners = [];
$configs = [];
foreach (array_keys($arguments[1]->getValues()) as $contextId) {
$contextDef = $container->getDefinition($contextId);
$arguments = $contextDef->getArguments();
$listeners[] = array_map('strval', $arguments['index_0']->getValues());
$configDef = $container->getDefinition((string) $arguments['index_3']);
$configs[] = array_values($configDef->getArguments());
}
$this->assertSame([[
'simple_auth',
'security.user_checker',
null,
true,
false,
'security.user.provider.concrete.default',
'simple_auth',
'security.authentication.form_entry_point.simple_auth',
null,
null,
['simple_form', 'anonymous',
],
null,
]], $configs);
$this->assertSame([[
'security.channel_listener',
'security.context_listener.0',
'security.authentication.listener.simple_form.simple_auth',
'security.authentication.listener.anonymous.simple_auth',
'security.access_listener',
]], $listeners);
}
/**
* @group legacy
* @expectedDeprecation Normalization of cookie names is deprecated since Symfony 4.3. Starting from Symfony 5.0, the "cookie1-name" cookie configured in "logout.delete_cookies" will delete the "cookie1-name" cookie instead of the "cookie1_name" cookie.

View File

@ -1,21 +0,0 @@
<?php
$container->loadFromExtension('security', [
'providers' => [
'default' => [
'memory' => [
'users' => [
'foo' => ['password' => 'foo', 'roles' => 'ROLE_USER'],
],
],
],
],
'firewalls' => [
'simple_auth' => [
'provider' => 'default',
'anonymous' => true,
'simple_form' => ['authenticator' => 'simple_authenticator'],
],
],
]);

View File

@ -1,21 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<container xmlns="http://symfony.com/schema/dic/services"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:sec="http://symfony.com/schema/dic/security"
xsi:schemaLocation="http://symfony.com/schema/dic/services https://symfony.com/schema/dic/services/services-1.0.xsd">
<sec:config>
<sec:provider name="default">
<sec:memory>
<sec:user name="foo" password="foo" roles="ROLE_USER" />
</sec:memory>
</sec:provider>
<sec:firewall name="simple_auth">
<sec:simple_form authenticator="simple_authenticator"/>
<sec:anonymous/>
</sec:firewall>
</sec:config>
</container>

View File

@ -1,12 +0,0 @@
security:
providers:
default:
memory:
users:
foo: { password: foo, roles: ROLE_USER }
firewalls:
simple_auth:
provider: default
anonymous: ~
simple_form: { authenticator: simple_authenticator }

View File

@ -7,6 +7,9 @@ CHANGELOG
* Removed `Argon2iPasswordEncoder`, use `SodiumPasswordEncoder` instead
* Removed `BcryptPasswordEncoder`, use `NativePasswordEncoder` instead
* Removed the `has_role()` function from security expressions, use `is_granted()` instead.
* `SimpleAuthenticatorInterface`, `SimpleFormAuthenticatorInterface`, `SimplePreAuthenticatorInterface`,
`SimpleAuthenticationProvider`, `SimpleAuthenticationHandler`, `SimpleFormAuthenticationListener` and
`SimplePreAuthenticationListener` have been removed. Use Guard instead.
4.3.0
-----

View File

@ -1,68 +0,0 @@
<?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\Component\Security\Core\Authentication\Provider;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserChecker;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', SimpleAuthenticationProvider::class), E_USER_DEPRECATED);
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
class SimpleAuthenticationProvider implements AuthenticationProviderInterface
{
private $simpleAuthenticator;
private $userProvider;
private $providerKey;
private $userChecker;
public function __construct(SimpleAuthenticatorInterface $simpleAuthenticator, UserProviderInterface $userProvider, string $providerKey, UserCheckerInterface $userChecker = null)
{
$this->simpleAuthenticator = $simpleAuthenticator;
$this->userProvider = $userProvider;
$this->providerKey = $providerKey;
$this->userChecker = $userChecker ?: new UserChecker();
}
public function authenticate(TokenInterface $token)
{
$authToken = $this->simpleAuthenticator->authenticateToken($token, $this->userProvider, $this->providerKey);
if (!$authToken instanceof TokenInterface) {
throw new AuthenticationException('Simple authenticator failed to return an authenticated token.');
}
$user = $authToken->getUser();
if (!$user instanceof UserInterface) {
return $authToken;
}
$this->userChecker->checkPreAuth($user);
$this->userChecker->checkPostAuth($user);
return $authToken;
}
public function supports(TokenInterface $token)
{
return $this->simpleAuthenticator->supportsToken($token, $this->providerKey);
}
}

View File

@ -1,27 +0,0 @@
<?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\Component\Security\Core\Authentication;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
interface SimpleAuthenticatorInterface
{
public function authenticateToken(TokenInterface $token, UserProviderInterface $userProvider, $providerKey);
public function supportsToken(TokenInterface $token, $providerKey);
}

View File

@ -1,107 +0,0 @@
<?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\Component\Security\Core\Tests\Authentication\Provider;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Core\Authentication\Provider\SimpleAuthenticationProvider;
use Symfony\Component\Security\Core\Exception\DisabledException;
use Symfony\Component\Security\Core\Exception\LockedException;
use Symfony\Component\Security\Core\User\UserChecker;
/**
* @group legacy
*/
class SimpleAuthenticationProviderTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\DisabledException
*/
public function testAuthenticateWhenPreChecksFails()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token->expects($this->any())
->method('getUser')
->willReturn($user);
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPreAuth')
->willThrowException(new DisabledException());
$authenticator = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface')->getMock();
$authenticator->expects($this->once())
->method('authenticateToken')
->willReturn($token);
$provider = $this->getProvider($authenticator, null, $userChecker);
$provider->authenticate($token);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LockedException
*/
public function testAuthenticateWhenPostChecksFails()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token->expects($this->any())
->method('getUser')
->willReturn($user);
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$userChecker->expects($this->once())
->method('checkPostAuth')
->willThrowException(new LockedException());
$authenticator = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface')->getMock();
$authenticator->expects($this->once())
->method('authenticateToken')
->willReturn($token);
$provider = $this->getProvider($authenticator, null, $userChecker);
$provider->authenticate($token);
}
public function testAuthenticateSkipsUserChecksForNonUserInterfaceObjects()
{
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token->expects($this->any())
->method('getUser')
->willReturn('string-user');
$authenticator = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface')->getMock();
$authenticator->expects($this->once())
->method('authenticateToken')
->willReturn($token);
$this->assertSame($token, $this->getProvider($authenticator, null, new UserChecker())->authenticate($token));
}
protected function getProvider($simpleAuthenticator = null, $userProvider = null, $userChecker = null, $key = 'test')
{
if (null === $userChecker) {
$userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
}
if (null === $simpleAuthenticator) {
$simpleAuthenticator = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface')->getMock();
}
if (null === $userProvider) {
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
}
return new SimpleAuthenticationProvider($simpleAuthenticator, $userProvider, $key, $userChecker);
}
}

View File

@ -1,108 +0,0 @@
<?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\Component\Security\Http\Authentication;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', SimpleAuthenticationHandler::class), E_USER_DEPRECATED);
/**
* Class to proxy authentication success/failure handlers.
*
* Events are sent to the SimpleAuthenticatorInterface if it implements
* the right interface, otherwise (or if it fails to return a Response)
* the default handlers are triggered.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
class SimpleAuthenticationHandler implements AuthenticationFailureHandlerInterface, AuthenticationSuccessHandlerInterface
{
protected $successHandler;
protected $failureHandler;
protected $simpleAuthenticator;
protected $logger;
/**
* @param SimpleAuthenticatorInterface $authenticator SimpleAuthenticatorInterface instance
* @param AuthenticationSuccessHandlerInterface $successHandler Default success handler
* @param AuthenticationFailureHandlerInterface $failureHandler Default failure handler
* @param LoggerInterface $logger Optional logger
*/
public function __construct(SimpleAuthenticatorInterface $authenticator, AuthenticationSuccessHandlerInterface $successHandler, AuthenticationFailureHandlerInterface $failureHandler, LoggerInterface $logger = null)
{
$this->simpleAuthenticator = $authenticator;
$this->successHandler = $successHandler;
$this->failureHandler = $failureHandler;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
if ($this->simpleAuthenticator instanceof AuthenticationSuccessHandlerInterface) {
if ($this->logger) {
$this->logger->debug('Selected an authentication success handler.', ['handler' => \get_class($this->simpleAuthenticator)]);
}
$response = $this->simpleAuthenticator->onAuthenticationSuccess($request, $token);
if ($response instanceof Response) {
return $response;
}
if (null !== $response) {
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationSuccess method must return null to use the default success handler, or a Response object', \get_class($this->simpleAuthenticator)));
}
}
if ($this->logger) {
$this->logger->debug('Fallback to the default authentication success handler.');
}
return $this->successHandler->onAuthenticationSuccess($request, $token);
}
/**
* {@inheritdoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ($this->simpleAuthenticator instanceof AuthenticationFailureHandlerInterface) {
if ($this->logger) {
$this->logger->debug('Selected an authentication failure handler.', ['handler' => \get_class($this->simpleAuthenticator)]);
}
$response = $this->simpleAuthenticator->onAuthenticationFailure($request, $exception);
if ($response instanceof Response) {
return $response;
}
if (null !== $response) {
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationFailure method must return null to use the default failure handler, or a Response object', \get_class($this->simpleAuthenticator)));
}
}
if ($this->logger) {
$this->logger->debug('Fallback to the default authentication failure handler.');
}
return $this->failureHandler->onAuthenticationFailure($request, $exception);
}
}

View File

@ -1,25 +0,0 @@
<?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\Component\Security\Http\Authentication;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
interface SimpleFormAuthenticatorInterface extends SimpleAuthenticatorInterface
{
public function createToken(Request $request, $username, $password, $providerKey);
}

View File

@ -1,25 +0,0 @@
<?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\Component\Security\Http\Authentication;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
interface SimplePreAuthenticatorInterface extends SimpleAuthenticatorInterface
{
public function createToken(Request $request, $providerKey);
}

View File

@ -1,116 +0,0 @@
<?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\Component\Security\Http\Firewall;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimpleFormAuthenticatorInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\ParameterBagUtils;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', SimpleFormAuthenticationListener::class), E_USER_DEPRECATED);
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
class SimpleFormAuthenticationListener extends AbstractAuthenticationListener
{
private $simpleAuthenticator;
private $csrfTokenManager;
/**
* @throws \InvalidArgumentException In case no simple authenticator is provided
*/
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, HttpUtils $httpUtils, string $providerKey, AuthenticationSuccessHandlerInterface $successHandler, AuthenticationFailureHandlerInterface $failureHandler, array $options = [], LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null, CsrfTokenManagerInterface $csrfTokenManager = null, SimpleFormAuthenticatorInterface $simpleAuthenticator = null)
{
if (!$simpleAuthenticator) {
throw new \InvalidArgumentException('Missing simple authenticator');
}
$this->simpleAuthenticator = $simpleAuthenticator;
$this->csrfTokenManager = $csrfTokenManager;
$options = array_merge([
'username_parameter' => '_username',
'password_parameter' => '_password',
'csrf_parameter' => '_csrf_token',
'csrf_token_id' => 'authenticate',
'post_only' => true,
], $options);
parent::__construct($tokenStorage, $authenticationManager, $sessionStrategy, $httpUtils, $providerKey, $successHandler, $failureHandler, $options, $logger, $dispatcher);
}
/**
* {@inheritdoc}
*/
protected function requiresAuthentication(Request $request)
{
if ($this->options['post_only'] && !$request->isMethod('POST')) {
return false;
}
return parent::requiresAuthentication($request);
}
/**
* {@inheritdoc}
*/
protected function attemptAuthentication(Request $request)
{
if (null !== $this->csrfTokenManager) {
$csrfToken = ParameterBagUtils::getRequestParameterValue($request, $this->options['csrf_parameter']);
if (false === $this->csrfTokenManager->isTokenValid(new CsrfToken($this->options['csrf_token_id'], $csrfToken))) {
throw new InvalidCsrfTokenException('Invalid CSRF token.');
}
}
if ($this->options['post_only']) {
$username = ParameterBagUtils::getParameterBagValue($request->request, $this->options['username_parameter']);
$password = ParameterBagUtils::getParameterBagValue($request->request, $this->options['password_parameter']);
} else {
$username = ParameterBagUtils::getRequestParameterValue($request, $this->options['username_parameter']);
$password = ParameterBagUtils::getRequestParameterValue($request, $this->options['password_parameter']);
}
if (!\is_string($username) && (!\is_object($username) || !\method_exists($username, '__toString'))) {
throw new BadRequestHttpException(sprintf('The key "%s" must be a string, "%s" given.', $this->options['username_parameter'], \gettype($username)));
}
$username = trim($username);
if (\strlen($username) > Security::MAX_USERNAME_LENGTH) {
throw new BadCredentialsException('Invalid username.');
}
$request->getSession()->set(Security::LAST_USERNAME, $username);
$token = $this->simpleAuthenticator->createToken($request, $username, $password, $this->providerKey);
return $this->authenticationManager->authenticate($token);
}
}

View File

@ -1,152 +0,0 @@
<?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\Component\Security\Http\Firewall;
use Psr\Log\LoggerInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\LegacyEventDispatcherProxy;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolver;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
@trigger_error(sprintf('The "%s" class is deprecated since Symfony 4.2, use Guard instead.', SimplePreAuthenticationListener::class), E_USER_DEPRECATED);
/**
* SimplePreAuthenticationListener implements simple proxying to an authenticator.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*
* @deprecated since Symfony 4.2, use Guard instead.
*/
class SimplePreAuthenticationListener implements ListenerInterface
{
use LegacyListenerTrait;
private $tokenStorage;
private $authenticationManager;
private $providerKey;
private $simpleAuthenticator;
private $logger;
private $dispatcher;
private $sessionStrategy;
private $trustResolver;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, string $providerKey, SimplePreAuthenticatorInterface $simpleAuthenticator, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null, AuthenticationTrustResolverInterface $trustResolver = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->providerKey = $providerKey;
$this->simpleAuthenticator = $simpleAuthenticator;
$this->logger = $logger;
$this->dispatcher = LegacyEventDispatcherProxy::decorate($dispatcher);
$this->trustResolver = $trustResolver ?: new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
}
/**
* Call this method if your authentication token is stored to a session.
*
* @final
*/
public function setSessionAuthenticationStrategy(SessionAuthenticationStrategyInterface $sessionStrategy)
{
$this->sessionStrategy = $sessionStrategy;
}
/**
* Handles basic authentication.
*/
public function __invoke(RequestEvent $event)
{
$request = $event->getRequest();
if (null !== $this->logger) {
$this->logger->info('Attempting SimplePreAuthentication.', ['key' => $this->providerKey, 'authenticator' => \get_class($this->simpleAuthenticator)]);
}
if ((null !== $token = $this->tokenStorage->getToken()) && !$this->trustResolver->isAnonymous($token)) {
return;
}
try {
$token = $this->simpleAuthenticator->createToken($request, $this->providerKey);
// allow null to be returned to skip authentication
if (null === $token) {
return;
}
$token = $this->authenticationManager->authenticate($token);
$this->migrateSession($request, $token);
$this->tokenStorage->setToken($token);
if (null !== $this->dispatcher) {
$loginEvent = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch($loginEvent, SecurityEvents::INTERACTIVE_LOGIN);
}
} catch (AuthenticationException $e) {
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info('SimplePreAuthentication request failed.', ['exception' => $e, 'authenticator' => \get_class($this->simpleAuthenticator)]);
}
if ($this->simpleAuthenticator instanceof AuthenticationFailureHandlerInterface) {
$response = $this->simpleAuthenticator->onAuthenticationFailure($request, $e);
if ($response instanceof Response) {
$event->setResponse($response);
} elseif (null !== $response) {
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationFailure method must return null or a Response object', \get_class($this->simpleAuthenticator)));
}
}
return;
}
if ($this->simpleAuthenticator instanceof AuthenticationSuccessHandlerInterface) {
$response = $this->simpleAuthenticator->onAuthenticationSuccess($request, $token);
if ($response instanceof Response) {
$event->setResponse($response);
} elseif (null !== $response) {
throw new \UnexpectedValueException(sprintf('The %s::onAuthenticationSuccess method must return null or a Response object', \get_class($this->simpleAuthenticator)));
}
}
}
private function migrateSession(Request $request, TokenInterface $token)
{
if (!$this->sessionStrategy || !$request->hasSession() || !$request->hasPreviousSession()) {
return;
}
$this->sessionStrategy->onAuthentication($request, $token);
}
}

View File

@ -1,199 +0,0 @@
<?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\Component\Security\Http\Tests;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\SimpleAuthenticationHandler;
/**
* @group legacy
*/
class SimpleAuthenticationHandlerTest extends TestCase
{
private $successHandler;
private $failureHandler;
private $request;
private $token;
private $authenticationException;
private $response;
protected function setUp()
{
$this->successHandler = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface')->getMock();
$this->failureHandler = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface')->getMock();
$this->request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$this->token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
// No methods are invoked on the exception; we just assert on its class
$this->authenticationException = new AuthenticationException();
$this->response = new Response();
}
public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfSimpleIsNotASuccessHandler()
{
$authenticator = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface')->getMock();
$this->successHandler->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationSuccess($this->request, $this->token);
$this->assertSame($this->response, $result);
}
public function testOnAuthenticationSuccessCallsSimpleAuthenticator()
{
$this->successHandler->expects($this->never())
->method('onAuthenticationSuccess');
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationSuccess($this->request, $this->token);
$this->assertSame($this->response, $result);
}
/**
* @expectedException \UnexpectedValueException
* @expectedExceptionMessage onAuthenticationSuccess method must return null to use the default success handler, or a Response object
*/
public function testOnAuthenticationSuccessThrowsAnExceptionIfNonResponseIsReturned()
{
$this->successHandler->expects($this->never())
->method('onAuthenticationSuccess');
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->willReturn(new \stdClass());
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$handler->onAuthenticationSuccess($this->request, $this->token);
}
public function testOnAuthenticationSuccessFallsBackToDefaultHandlerIfNullIsReturned()
{
$this->successHandler->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->willReturn($this->response);
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->willReturn(null);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationSuccess($this->request, $this->token);
$this->assertSame($this->response, $result);
}
public function testOnAuthenticationFailureFallsBackToDefaultHandlerIfSimpleIsNotAFailureHandler()
{
$authenticator = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface')->getMock();
$this->failureHandler->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);
$this->assertSame($this->response, $result);
}
public function testOnAuthenticationFailureCallsSimpleAuthenticator()
{
$this->failureHandler->expects($this->never())
->method('onAuthenticationFailure');
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->willReturn($this->response);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);
$this->assertSame($this->response, $result);
}
/**
* @expectedException \UnexpectedValueException
* @expectedExceptionMessage onAuthenticationFailure method must return null to use the default failure handler, or a Response object
*/
public function testOnAuthenticationFailureThrowsAnExceptionIfNonResponseIsReturned()
{
$this->failureHandler->expects($this->never())
->method('onAuthenticationFailure');
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->willReturn(new \stdClass());
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$handler->onAuthenticationFailure($this->request, $this->authenticationException);
}
public function testOnAuthenticationFailureFallsBackToDefaultHandlerIfNullIsReturned()
{
$this->failureHandler->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->willReturn($this->response);
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->willReturn(null);
$handler = new SimpleAuthenticationHandler($authenticator, $this->successHandler, $this->failureHandler);
$result = $handler->onAuthenticationFailure($this->request, $this->authenticationException);
$this->assertSame($this->response, $result);
}
}
interface TestSuccessHandlerInterface extends AuthenticationSuccessHandlerInterface, SimpleAuthenticatorInterface
{
}
interface TestFailureHandlerInterface extends AuthenticationFailureHandlerInterface, SimpleAuthenticatorInterface
{
}

View File

@ -1,133 +0,0 @@
<?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\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\Firewall\SimplePreAuthenticationListener;
use Symfony\Component\Security\Http\SecurityEvents;
/**
* @group legacy
*/
class SimplePreAuthenticationListenerTest extends TestCase
{
private $authenticationManager;
private $dispatcher;
private $event;
private $logger;
private $request;
private $tokenStorage;
private $token;
public function testHandle()
{
$this->tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($this->token))
;
$this->authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->equalTo($this->token))
->willReturn($this->token)
;
$simpleAuthenticator = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface')->getMock();
$simpleAuthenticator
->expects($this->once())
->method('createToken')
->with($this->equalTo($this->request), $this->equalTo('secured_area'))
->willReturn($this->token)
;
$loginEvent = new InteractiveLoginEvent($this->request, $this->token);
$this->dispatcher
->expects($this->once())
->method('dispatch')
->with($this->equalTo($loginEvent), $this->equalTo(SecurityEvents::INTERACTIVE_LOGIN))
;
$listener = new SimplePreAuthenticationListener($this->tokenStorage, $this->authenticationManager, 'secured_area', $simpleAuthenticator, $this->logger, $this->dispatcher);
$listener($this->event);
}
public function testHandlecatchAuthenticationException()
{
$exception = new AuthenticationException('Authentication failed.');
$this->authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->equalTo($this->token))
->willThrowException($exception)
;
$this->tokenStorage->expects($this->once())
->method('setToken')
->with($this->equalTo(null))
;
$simpleAuthenticator = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface')->getMock();
$simpleAuthenticator
->expects($this->once())
->method('createToken')
->with($this->equalTo($this->request), $this->equalTo('secured_area'))
->willReturn($this->token)
;
$listener = new SimplePreAuthenticationListener($this->tokenStorage, $this->authenticationManager, 'secured_area', $simpleAuthenticator, $this->logger, $this->dispatcher);
$listener($this->event);
}
protected function setUp()
{
$this->authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager')
->disableOriginalConstructor()
->getMock()
;
$this->dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$this->request = new Request([], [], [], [], [], []);
$this->event = $this->getMockBuilder(RequestEvent::class)->disableOriginalConstructor()->getMock();
$this->event
->expects($this->any())
->method('getRequest')
->willReturn($this->request)
;
$this->logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$this->tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$this->token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
}
protected function tearDown()
{
$this->authenticationManager = null;
$this->dispatcher = null;
$this->event = null;
$this->logger = null;
$this->request = null;
$this->tokenStorage = null;
$this->token = null;
}
}