Skip to content

[Security] SoC - Move authentication target url generation out of the authentication listener #98

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
wants to merge 1 commit into from
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 @@ -26,25 +26,31 @@
*/
abstract class AbstractFactory implements SecurityFactoryInterface
{
protected $options = array(
protected $listenerOptions = array(
'check_path' => '/login_check',
'login_path' => '/login',
'use_forward' => false,
'failure_path' => null,
'failure_forward' => false,
);

protected $targetUrlGeneratorOptions = array(
'always_use_default_target_path' => false,
'default_target_path' => '/',
'target_path_parameter' => '_target_path',
'use_referer' => false,
'failure_path' => null,
'failure_forward' => false,
'use_referer' => false
);

public function create(ContainerBuilder $container, $id, $config, $userProviderId, $defaultEntryPointId)
{
// authentication provider
$authProviderId = $this->createAuthProvider($container, $id, $config, $userProviderId);

// target url generator
$targetUrlGeneratorId = $this->createTargetUrlGenerator($container, $id, $config);

// authentication listener
$listenerId = $this->createListener($container, $id, $config, $userProviderId);
$listenerId = $this->createListener($container, $id, $config, $userProviderId, $targetUrlGeneratorId);

// add remember-me aware tag if requested
if ($this->isRememberMeAware($config)) {
Expand All @@ -69,7 +75,7 @@ public function addConfiguration(NodeBuilder $node)
->scalarNode('failure_handler')->end()
;

foreach ($this->options as $name => $default) {
foreach (array_merge($this->listenerOptions, $this->targetUrlGeneratorOptions) as $name => $default) {
if (is_bool($default)) {
$node->booleanNode($name)->defaultValue($default);
} else {
Expand All @@ -80,7 +86,7 @@ public function addConfiguration(NodeBuilder $node)

public final function addOption($name, $default = null)
{
$this->options[$name] = $default;
$this->listenerOptions[$name] = $default;
}

/**
Expand Down Expand Up @@ -142,26 +148,38 @@ protected function isRememberMeAware($config)
return $config['remember_me'];
}

protected function createListener($container, $id, $config, $userProvider)
protected function createListener($container, $id, $config, $userProvider, $targetUrlGenerator)
{
$listenerId = $this->getListenerId();
$listener = new DefinitionDecorator($listenerId);
$listener->setArgument(3, $id);
$listener->setArgument(4, array_intersect_key($config, $this->options));
$listener->setArgument(3, new Reference($targetUrlGenerator));
$listener->setArgument(4, $id);
$listener->setArgument(5, array_intersect_key($config, $this->listenerOptions));

// success handler
if (isset($config['success_handler'])) {
$listener->setArgument(5, new Reference($config['success_handler']));
$listener->setArgument(6, new Reference($config['success_handler']));
}

// failure handler
if (isset($config['failure_handler'])) {
$listener->setArgument(6, new Reference($config['failure_handler']));
$listener->setArgument(7, new Reference($config['failure_handler']));
}

$listenerId .= '.'.$id;
$container->setDefinition($listenerId, $listener);

return $listenerId;
}

public function createTargetUrlGenerator(ContainerBuilder $container, $id, $config)
{
$targetUrlGeneratorId = 'security.authentication.target_url_generator.'.$id;
$container
->setDefinition($targetUrlGeneratorId, new DefinitionDecorator('security.authentication.target_url_generator'))
->addArgument(array_intersect_key($config, $this->targetUrlGeneratorOptions))
;

return $targetUrlGeneratorId;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -69,9 +69,9 @@ protected function createAuthProvider(ContainerBuilder $container, $id, $config,
return $provider;
}

protected function createListener($container, $id, $config, $userProvider)
protected function createListener($container, $id, $config, $userProvider, $targetUrlGenerator)
{
$listenerId = parent::createListener($container, $id, $config, $userProvider);
$listenerId = parent::createListener($container, $id, $config, $userProvider, $targetUrlGenerator);

if (isset($config['csrf_provider'])) {
$container
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
<parameter key="security.channel_listener.class">Symfony\Component\Security\Http\Firewall\ChannelListener</parameter>

<parameter key="security.authentication.form_entry_point.class">Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint</parameter>
<parameter key="security.authentication.target_url_generator.class">Symfony\Component\Security\Http\Authentication\TargetUrlGenerator</parameter>
<parameter key="security.authentication.listener.form.class">Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener</parameter>

<parameter key="security.authentication.listener.basic.class">Symfony\Component\Security\Http\Firewall\BasicAuthenticationListener</parameter>
Expand All @@ -26,7 +27,7 @@
<parameter key="security.authentication.x509.credentials">SSL_CLIENT_S_DN</parameter>

<parameter key="security.authentication.listener.anonymous.class">Symfony\Component\Security\Http\Firewall\AnonymousAuthenticationListener</parameter>

<parameter key="security.authentication.switchuser_listener.class">Symfony\Component\Security\Http\Firewall\SwitchUserListener</parameter>

<parameter key="security.logout_listener.class">Symfony\Component\Security\Http\Firewall\LogoutListener</parameter>
Expand All @@ -44,7 +45,7 @@
<parameter key="security.authentication.provider.anonymous">Symfony\Component\Security\Core\Authentication\Provider\AnonymousAuthenticationProvider</parameter>
<parameter key="security.anonymous.key">SomeRandomValue</parameter>
</parameters>

<services>
<service id="security.authentication.listener.anonymous" class="%security.authentication.listener.anonymous.class%" public="false">
<argument type="service" id="security.context" />
Expand Down Expand Up @@ -93,19 +94,22 @@

<service id="security.authentication.form_entry_point" class="%security.authentication.form_entry_point.class%" public="false" abstract="true" />

<service id="security.authentication.target_url_generator" class="%security.authentication.target_url_generator.class%" public="false" abstract="true" />

<service id="security.authentication.listener.abstract" abstract="true" public="false">
<argument type="service" id="security.context" />
<argument type="service" id="security.authentication.manager" />
<argument type="service" id="security.authentication.session_strategy" />
<argument type="service" id="security.authentication.target_url_generator" />
<argument />
<argument type="collection"></argument>
<argument type="service" id="security.authentication.success_handler" on-invalid="null" />
<argument type="service" id="security.authentication.failure_handler" on-invalid="null" />
<argument type="service" id="logger" on-invalid="null" />
</service>

<service id="security.authentication.listener.form"
class="%security.authentication.listener.form.class%"
<service id="security.authentication.listener.form"
class="%security.authentication.listener.form.class%"
parent="security.authentication.listener.abstract"
abstract="true">
</service>
Expand Down Expand Up @@ -134,19 +138,19 @@
<argument type="service" id="security.authentication.digest_entry_point" />
<argument type="service" id="logger" on-invalid="null" />
</service>

<service id="security.authentication.provider.dao" class="%security.authentication.provider.dao.class%" abstract="true" public="false">
<argument /> <!-- User Provider -->
<argument type="service" id="security.account_checker" />
<argument /> <!-- Provider-shared Key -->
<argument type="service" id="security.encoder_factory" />
</service>

<service id="security.authentication.provider.pre_authenticated" class="%security.authentication.provider.pre_authenticated.class%" abstract="true" public="false">
<argument /> <!-- User Provider -->
<argument type="service" id="security.account_checker" />
</service>

<service id="security.exception_listener" class="%security.exception_listener.class%" public="false" abstract="true">
<argument type="service" id="security.context" />
<argument type="service" id="security.authentication.trust_resolver" />
Expand All @@ -173,4 +177,4 @@
<argument type="service" id="logger" on-invalid="null" />
</service>
</services>
</container>
</container>
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ interface AuthenticationSuccessHandlerInterface
* is called by authentication listeners inheriting from
* AbstractAuthenticationListener.
*
* @param EventInterface $event the "core.security" event, this event always
* @param EventInterface $event the "core.security" event, this event always
* has the kernel as target
* @param Request $request
* @param TokenInterface $token
* @param Request $request
* @param TokenInterface $token
* @param TargetUrlGenerator $targetUrlGenerator - has a determineTargetUrl method
*
* @return Response the response to return
*/
function onAuthenticationSuccess(EventInterface $event, Request $request, TokenInterface $token);
}
function onAuthenticationSuccess(EventInterface $event, Request $request, TokenInterface $token, TargetUrlGenerator $targetUrlGenerator);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
<?php

/*
* This file is part of the Symfony package.
*
* (c) Fabien Potencier <fabien.potencier@symfony-project.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;

/**
* TargetUrlGenerator determines the authentication target url
*
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Thibault Duplessis <thibault.duplessis@gmail.com>
*/
class TargetUrlGenerator
{
protected $options;

public function __construct($options)
{
$this->options = $options;
}

/**
* Builds the target URL according to the defined options.
*
* @param Request $request
*
* @return string
*/
public function determineTargetUrl(Request $request)
{
if ($this->options['always_use_default_target_path']) {
return $this->options['default_target_path'];
}

if ($targetUrl = $request->get($this->options['target_path_parameter'])) {
return $targetUrl;
}

$session = $request->getSession();
if ($targetUrl = $session->get('_security.target_path')) {
$session->remove('_security.target_path');

return $targetUrl;
}

if ($this->options['use_referer'] && $targetUrl = $request->headers->get('Referer')) {
return $targetUrl;
}

return $this->options['default_target_path'];
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\TargetUrlGenerator;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
Expand Down Expand Up @@ -50,6 +51,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
protected $securityContext;
protected $authenticationManager;
protected $sessionStrategy;
protected $targetUrlGenerator;
protected $providerKey;
protected $eventDispatcher;
protected $options;
Expand All @@ -66,7 +68,7 @@ abstract class AbstractAuthenticationListener implements ListenerInterface
* @param array $options An array of options for the processing of a successful, or failed authentication attempt
* @param LoggerInterface $logger A LoggerInterface instance
*/
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, $providerKey, array $options = array(), AuthenticationSuccessHandlerInterface $successHandler = null, AuthenticationFailureHandlerInterface $failureHandler = null, LoggerInterface $logger = null)
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, TargetUrlGenerator $targetUrlGenerator, $providerKey, array $options = array(), AuthenticationSuccessHandlerInterface $successHandler = null, AuthenticationFailureHandlerInterface $failureHandler = null, LoggerInterface $logger = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
Expand All @@ -75,6 +77,7 @@ public function __construct(SecurityContextInterface $securityContext, Authentic
$this->securityContext = $securityContext;
$this->authenticationManager = $authenticationManager;
$this->sessionStrategy = $sessionStrategy;
$this->targetUrlGenerator = $targetUrlGenerator;
$this->providerKey = $providerKey;
$this->successHandler = $successHandler;
$this->failureHandler = $failureHandler;
Expand Down Expand Up @@ -226,9 +229,9 @@ protected function onSuccess(EventInterface $event, Request $request, TokenInter
}

if (null !== $this->successHandler) {
$response = $this->successHandler->onAuthenticationSuccess($event, $request, $token);
$response = $this->successHandler->onAuthenticationSuccess($event, $request, $token, $this->targetUrlGenerator);
} else {
$path = $this->determineTargetUrl($request);
$path = $this->targetUrlGenerator->determineTargetUrl($request);
$response = new RedirectResponse(0 !== strpos($path, 'http') ? $request->getUriForPath($path) : $path, 302);
}

Expand All @@ -239,37 +242,6 @@ protected function onSuccess(EventInterface $event, Request $request, TokenInter
return $response;
}

/**
* Builds the target URL according to the defined options.
*
* @param Request $request
*
* @return string
*/
protected function determineTargetUrl(Request $request)
{
if ($this->options['always_use_default_target_path']) {
return $this->options['default_target_path'];
}

if ($targetUrl = $request->get($this->options['target_path_parameter'])) {
return $targetUrl;
}

$session = $request->getSession();
if ($targetUrl = $session->get('_security.target_path')) {
$session->remove('_security.target_path');

return $targetUrl;
}

if ($this->options['use_referer'] && $targetUrl = $request->headers->get('Referer')) {
return $targetUrl;
}

return $this->options['default_target_path'];
}

/**
* Performs authentication.
*
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
use Symfony\Component\HttpKernel\Log\LoggerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface;
use Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface;
use Symfony\Component\Security\Http\Authentication\TargetUrlGenerator;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
Expand All @@ -35,9 +36,9 @@ class UsernamePasswordFormAuthenticationListener extends AbstractAuthenticationL
/**
* {@inheritdoc}
*/
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, $providerKey, array $options = array(), AuthenticationSuccessHandlerInterface $successHandler = null, AuthenticationFailureHandlerInterface $failureHandler = null, LoggerInterface $logger = null, CsrfProviderInterface $csrfProvider = null)
public function __construct(SecurityContextInterface $securityContext, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, TargetUrlGenerator $targetUrlGenerator, $providerKey, array $options = array(), AuthenticationSuccessHandlerInterface $successHandler = null, AuthenticationFailureHandlerInterface $failureHandler = null, LoggerInterface $logger = null, CsrfProviderInterface $csrfProvider = null)
{
parent::__construct($securityContext, $authenticationManager, $sessionStrategy, $providerKey, array_merge(array(
parent::__construct($securityContext, $authenticationManager, $sessionStrategy, $targetUrlGenerator, $providerKey, array_merge(array(
'username_parameter' => '_username',
'password_parameter' => '_password',
'csrf_parameter' => '_csrf_token',
Expand Down