This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,3 @@
vendor/
composer.lock
phpunit.xml

View File

@@ -0,0 +1,52 @@
<?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;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* AccessMap allows configuration of different access control rules for
* specific parts of the website.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AccessMap implements AccessMapInterface
{
private $map = array();
/**
* Constructor.
*
* @param RequestMatcherInterface $requestMatcher A RequestMatcherInterface instance
* @param array $attributes An array of attributes to pass to the access decision manager (like roles)
* @param string|null $channel The channel to enforce (http, https, or null)
*/
public function add(RequestMatcherInterface $requestMatcher, array $attributes = array(), $channel = null)
{
$this->map[] = array($requestMatcher, $attributes, $channel);
}
/**
* {@inheritdoc}
*/
public function getPatterns(Request $request)
{
foreach ($this->map as $elements) {
if (null === $elements[0] || $elements[0]->matches($request)) {
return array($elements[1], $elements[2]);
}
}
return array(null, null);
}
}

View File

@@ -0,0 +1,33 @@
<?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;
use Symfony\Component\HttpFoundation\Request;
/**
* AccessMap allows configuration of different access control rules for
* specific parts of the website.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Kris Wallsmith <kris@symfony.com>
*/
interface AccessMapInterface
{
/**
* Returns security attributes and required channel for the supplied request.
*
* @param Request $request The current request
*
* @return array A tuple of security attributes and the required channel
*/
public function getPatterns(Request $request);
}

View File

@@ -0,0 +1,40 @@
<?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\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Interface for custom authentication failure handlers.
*
* If you want to customize the failure handling process, instead of
* overwriting the respective listener globally, you can set a custom failure
* handler which implements this interface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface AuthenticationFailureHandlerInterface
{
/**
* This is called when an interactive authentication attempt fails. This is
* called by authentication listeners inheriting from
* AbstractAuthenticationListener.
*
* @param Request $request
* @param AuthenticationException $exception
*
* @return Response The response to return, never null
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception);
}

View File

@@ -0,0 +1,40 @@
<?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\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Interface for a custom authentication success handler.
*
* If you want to customize the success handling process, instead of
* overwriting the respective listener globally, you can set a custom success
* handler which implements this interface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface AuthenticationSuccessHandlerInterface
{
/**
* This is called when an interactive authentication attempt succeeds. This
* is called by authentication listeners inheriting from
* AbstractAuthenticationListener.
*
* @param Request $request
* @param TokenInterface $token
*
* @return Response never null
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token);
}

View File

@@ -0,0 +1,94 @@
<?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\HttpFoundation\RequestStack;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
/**
* Extracts Security Errors from Request.
*
* @author Boris Vujicic <boris.vujicic@gmail.com>
*/
class AuthenticationUtils
{
/**
* @var RequestStack
*/
private $requestStack;
/**
* @param RequestStack $requestStack
*/
public function __construct(RequestStack $requestStack)
{
$this->requestStack = $requestStack;
}
/**
* @param bool $clearSession
*
* @return AuthenticationException|null
*/
public function getLastAuthenticationError($clearSession = true)
{
$request = $this->getRequest();
$session = $request->getSession();
$authenticationException = null;
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$authenticationException = $request->attributes->get(Security::AUTHENTICATION_ERROR);
} elseif ($session !== null && $session->has(Security::AUTHENTICATION_ERROR)) {
$authenticationException = $session->get(Security::AUTHENTICATION_ERROR);
if ($clearSession) {
$session->remove(Security::AUTHENTICATION_ERROR);
}
}
return $authenticationException;
}
/**
* @return string
*/
public function getLastUsername()
{
$request = $this->getRequest();
if ($request->attributes->has(Security::LAST_USERNAME)) {
return $request->attributes->get(Security::LAST_USERNAME);
}
$session = $request->getSession();
return null === $session ? '' : $session->get(Security::LAST_USERNAME);
}
/**
* @return Request
*
* @throws \LogicException
*/
private function getRequest()
{
$request = $this->requestStack->getCurrentRequest();
if (null === $request) {
throw new \LogicException('Request should exist so it can be processed for error.');
}
return $request;
}
}

View File

@@ -0,0 +1,45 @@
<?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\Exception\AuthenticationException;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class CustomAuthenticationFailureHandler implements AuthenticationFailureHandlerInterface
{
private $handler;
/**
* Constructor.
*
* @param AuthenticationFailureHandlerInterface $handler An AuthenticationFailureHandlerInterface instance
* @param array $options Options for processing a successful authentication attempt
*/
public function __construct(AuthenticationFailureHandlerInterface $handler, array $options)
{
$this->handler = $handler;
if (method_exists($handler, 'setOptions')) {
$this->handler->setOptions($options);
}
}
/**
* {@inheritdoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
return $this->handler->onAuthenticationFailure($request, $exception);
}
}

View File

@@ -0,0 +1,49 @@
<?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\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* @author Fabien Potencier <fabien@symfony.com>
*/
class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
private $handler;
/**
* Constructor.
*
* @param AuthenticationSuccessHandlerInterface $handler An AuthenticationSuccessHandlerInterface instance
* @param array $options Options for processing a successful authentication attempt
* @param string $providerKey The provider key
*/
public function __construct(AuthenticationSuccessHandlerInterface $handler, array $options, $providerKey)
{
$this->handler = $handler;
if (method_exists($handler, 'setOptions')) {
$this->handler->setOptions($options);
}
if (method_exists($handler, 'setProviderKey')) {
$this->handler->setProviderKey($providerKey);
}
}
/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
return $this->handler->onAuthenticationSuccess($request, $token);
}
}

View File

@@ -0,0 +1,113 @@
<?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\HttpKernel\HttpKernelInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\ParameterBagUtils;
/**
* Class with the default authentication failure handling logic.
*
* Can be optionally be extended from by the developer to alter the behaviour
* while keeping the default behaviour.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class DefaultAuthenticationFailureHandler implements AuthenticationFailureHandlerInterface
{
protected $httpKernel;
protected $httpUtils;
protected $logger;
protected $options;
protected $defaultOptions = array(
'failure_path' => null,
'failure_forward' => false,
'login_path' => '/login',
'failure_path_parameter' => '_failure_path',
);
/**
* Constructor.
*
* @param HttpKernelInterface $httpKernel
* @param HttpUtils $httpUtils
* @param array $options Options for processing a failed authentication attempt
* @param LoggerInterface $logger Optional logger
*/
public function __construct(HttpKernelInterface $httpKernel, HttpUtils $httpUtils, array $options = array(), LoggerInterface $logger = null)
{
$this->httpKernel = $httpKernel;
$this->httpUtils = $httpUtils;
$this->logger = $logger;
$this->setOptions($options);
}
/**
* Gets the options.
*
* @return array An array of options
*/
public function getOptions()
{
return $this->options;
}
/**
* Sets the options.
*
* @param array $options An array of options
*/
public function setOptions(array $options)
{
$this->options = array_merge($this->defaultOptions, $options);
}
/**
* {@inheritdoc}
*/
public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
{
if ($failureUrl = ParameterBagUtils::getRequestParameterValue($request, $this->options['failure_path_parameter'])) {
$this->options['failure_path'] = $failureUrl;
}
if (null === $this->options['failure_path']) {
$this->options['failure_path'] = $this->options['login_path'];
}
if ($this->options['failure_forward']) {
if (null !== $this->logger) {
$this->logger->debug('Authentication failure, forward triggered.', array('failure_path' => $this->options['failure_path']));
}
$subRequest = $this->httpUtils->createRequest($request, $this->options['failure_path']);
$subRequest->attributes->set(Security::AUTHENTICATION_ERROR, $exception);
return $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
}
if (null !== $this->logger) {
$this->logger->debug('Authentication failure, redirect triggered.', array('failure_path' => $this->options['failure_path']));
}
$request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
return $this->httpUtils->createRedirectResponse($request, $this->options['failure_path']);
}
}

View File

@@ -0,0 +1,137 @@
<?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\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\ParameterBagUtils;
/**
* Class with the default authentication success handling logic.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class DefaultAuthenticationSuccessHandler implements AuthenticationSuccessHandlerInterface
{
use TargetPathTrait;
protected $httpUtils;
protected $options;
protected $providerKey;
protected $defaultOptions = array(
'always_use_default_target_path' => false,
'default_target_path' => '/',
'login_path' => '/login',
'target_path_parameter' => '_target_path',
'use_referer' => false,
);
/**
* Constructor.
*
* @param HttpUtils $httpUtils
* @param array $options Options for processing a successful authentication attempt
*/
public function __construct(HttpUtils $httpUtils, array $options = array())
{
$this->httpUtils = $httpUtils;
$this->setOptions($options);
}
/**
* {@inheritdoc}
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
return $this->httpUtils->createRedirectResponse($request, $this->determineTargetUrl($request));
}
/**
* Gets the options.
*
* @return array An array of options
*/
public function getOptions()
{
return $this->options;
}
/**
* Sets the options.
*
* @param array $options An array of options
*/
public function setOptions(array $options)
{
$this->options = array_merge($this->defaultOptions, $options);
}
/**
* Get the provider key.
*
* @return string
*/
public function getProviderKey()
{
return $this->providerKey;
}
/**
* Set the provider key.
*
* @param string $providerKey
*/
public function setProviderKey($providerKey)
{
$this->providerKey = $providerKey;
}
/**
* 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 = ParameterBagUtils::getRequestParameterValue($request, $this->options['target_path_parameter'])) {
return $targetUrl;
}
if (null !== $this->providerKey && $targetUrl = $this->getTargetPath($request->getSession(), $this->providerKey)) {
$this->removeTargetPath($request->getSession(), $this->providerKey);
return $targetUrl;
}
if ($this->options['use_referer']) {
$targetUrl = $request->headers->get('Referer');
if (false !== $pos = strpos($targetUrl, '?')) {
$targetUrl = substr($targetUrl, 0, $pos);
}
if ($targetUrl !== $this->httpUtils->generateUri($request, $this->options['login_path'])) {
return $targetUrl;
}
}
return $this->options['default_target_path'];
}
}

View File

@@ -0,0 +1,106 @@
<?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\HttpFoundation\Response;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authentication\SimpleAuthenticatorInterface;
/**
* 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>
*/
class SimpleAuthenticationHandler implements AuthenticationFailureHandlerInterface, AuthenticationSuccessHandlerInterface
{
protected $successHandler;
protected $failureHandler;
protected $simpleAuthenticator;
protected $logger;
/**
* Constructor.
*
* @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.', array('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.', array('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

@@ -0,0 +1,23 @@
<?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>
*/
interface SimpleFormAuthenticatorInterface extends SimpleAuthenticatorInterface
{
public function createToken(Request $request, $username, $password, $providerKey);
}

View File

@@ -0,0 +1,23 @@
<?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>
*/
interface SimplePreAuthenticatorInterface extends SimpleAuthenticatorInterface
{
public function createToken(Request $request, $providerKey);
}

View File

@@ -0,0 +1,35 @@
<?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\Authorization;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* This is used by the ExceptionListener to translate an AccessDeniedException
* to a Response object.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface AccessDeniedHandlerInterface
{
/**
* Handles an access denied failure.
*
* @param Request $request
* @param AccessDeniedException $accessDeniedException
*
* @return Response may return null
*/
public function handle(Request $request, AccessDeniedException $accessDeniedException);
}

View File

@@ -0,0 +1,45 @@
<?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\EntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* Implement this interface for any classes that will be called to "start"
* the authentication process (see method for more details).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
interface AuthenticationEntryPointInterface
{
/**
* Returns a response that directs the user to authenticate.
*
* This is called when an anonymous request accesses a resource that
* requires authentication. The job of this method is to return some
* response that "helps" the user start into the authentication process.
*
* Examples:
* A) For a form login, you might redirect to the login page
* return new RedirectResponse('/login');
* B) For an API token authentication system, you return a 401 response
* return new Response('Auth header required', 401);
*
* @param Request $request The request that resulted in an AuthenticationException
* @param AuthenticationException $authException The exception that started the authentication process
*
* @return Response
*/
public function start(Request $request, AuthenticationException $authException = null);
}

View File

@@ -0,0 +1,43 @@
<?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\EntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* BasicAuthenticationEntryPoint starts an HTTP Basic authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class BasicAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
private $realmName;
public function __construct($realmName)
{
$this->realmName = $realmName;
}
/**
* {@inheritdoc}
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$response = new Response();
$response->headers->set('WWW-Authenticate', sprintf('Basic realm="%s"', $this->realmName));
$response->setStatusCode(401);
return $response;
}
}

View File

@@ -0,0 +1,82 @@
<?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\EntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Psr\Log\LoggerInterface;
/**
* DigestAuthenticationEntryPoint starts an HTTP Digest authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DigestAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
private $secret;
private $realmName;
private $nonceValiditySeconds;
private $logger;
public function __construct($realmName, $secret, $nonceValiditySeconds = 300, LoggerInterface $logger = null)
{
$this->realmName = $realmName;
$this->secret = $secret;
$this->nonceValiditySeconds = $nonceValiditySeconds;
$this->logger = $logger;
}
/**
* {@inheritdoc}
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$expiryTime = microtime(true) + $this->nonceValiditySeconds * 1000;
$signatureValue = md5($expiryTime.':'.$this->secret);
$nonceValue = $expiryTime.':'.$signatureValue;
$nonceValueBase64 = base64_encode($nonceValue);
$authenticateHeader = sprintf('Digest realm="%s", qop="auth", nonce="%s"', $this->realmName, $nonceValueBase64);
if ($authException instanceof NonceExpiredException) {
$authenticateHeader .= ', stale="true"';
}
if (null !== $this->logger) {
$this->logger->debug('WWW-Authenticate header sent.', array('header' => $authenticateHeader));
}
$response = new Response();
$response->headers->set('WWW-Authenticate', $authenticateHeader);
$response->setStatusCode(401);
return $response;
}
/**
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* @return string
*/
public function getRealmName()
{
return $this->realmName;
}
}

View File

@@ -0,0 +1,65 @@
<?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\EntryPoint;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpKernel\HttpKernelInterface;
/**
* FormAuthenticationEntryPoint starts an authentication via a login form.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FormAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
private $loginPath;
private $useForward;
private $httpKernel;
private $httpUtils;
/**
* Constructor.
*
* @param HttpKernelInterface $kernel
* @param HttpUtils $httpUtils An HttpUtils instance
* @param string $loginPath The path to the login form
* @param bool $useForward Whether to forward or redirect to the login form
*/
public function __construct(HttpKernelInterface $kernel, HttpUtils $httpUtils, $loginPath, $useForward = false)
{
$this->httpKernel = $kernel;
$this->httpUtils = $httpUtils;
$this->loginPath = $loginPath;
$this->useForward = (bool) $useForward;
}
/**
* {@inheritdoc}
*/
public function start(Request $request, AuthenticationException $authException = null)
{
if ($this->useForward) {
$subRequest = $this->httpUtils->createRequest($request, $this->loginPath);
$response = $this->httpKernel->handle($subRequest, HttpKernelInterface::SUB_REQUEST);
if (200 === $response->getStatusCode()) {
$response->headers->set('X-Status-Code', 401);
}
return $response;
}
return $this->httpUtils->createRedirectResponse($request, $this->loginPath);
}
}

View File

@@ -0,0 +1,59 @@
<?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\EntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
/**
* RetryAuthenticationEntryPoint redirects URL based on the configured scheme.
*
* This entry point is not intended to work with HTTP post requests.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class RetryAuthenticationEntryPoint implements AuthenticationEntryPointInterface
{
private $httpPort;
private $httpsPort;
public function __construct($httpPort = 80, $httpsPort = 443)
{
$this->httpPort = $httpPort;
$this->httpsPort = $httpsPort;
}
/**
* {@inheritdoc}
*/
public function start(Request $request, AuthenticationException $authException = null)
{
$scheme = $request->isSecure() ? 'http' : 'https';
if ('http' === $scheme && 80 != $this->httpPort) {
$port = ':'.$this->httpPort;
} elseif ('https' === $scheme && 443 != $this->httpsPort) {
$port = ':'.$this->httpsPort;
} else {
$port = '';
}
$qs = $request->getQueryString();
if (null !== $qs) {
$qs = '?'.$qs;
}
$url = $scheme.'://'.$request->getHost().$port.$request->getBaseUrl().$request->getPathInfo().$qs;
return new RedirectResponse($url, 301);
}
}

View File

@@ -0,0 +1,59 @@
<?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\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\Event;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* InteractiveLoginEvent.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class InteractiveLoginEvent extends Event
{
private $request;
private $authenticationToken;
/**
* Constructor.
*
* @param Request $request A Request instance
* @param TokenInterface $authenticationToken A TokenInterface instance
*/
public function __construct(Request $request, TokenInterface $authenticationToken)
{
$this->request = $request;
$this->authenticationToken = $authenticationToken;
}
/**
* Gets the request.
*
* @return Request A Request instance
*/
public function getRequest()
{
return $this->request;
}
/**
* Gets the authentication token.
*
* @return TokenInterface A TokenInterface instance
*/
public function getAuthenticationToken()
{
return $this->authenticationToken;
}
}

View File

@@ -0,0 +1,49 @@
<?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\Event;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\EventDispatcher\Event;
/**
* SwitchUserEvent.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SwitchUserEvent extends Event
{
private $request;
private $targetUser;
public function __construct(Request $request, UserInterface $targetUser)
{
$this->request = $request;
$this->targetUser = $targetUser;
}
/**
* @return Request
*/
public function getRequest()
{
return $this->request;
}
/**
* @return UserInterface
*/
public function getTargetUser()
{
return $this->targetUser;
}
}

View File

@@ -0,0 +1,97 @@
<?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;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FinishRequestEvent;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Firewall uses a FirewallMap to register security listeners for the given
* request.
*
* It allows for different security strategies within the same application
* (a Basic authentication for the /api, and a web based authentication for
* everything else for instance).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class Firewall implements EventSubscriberInterface
{
private $map;
private $dispatcher;
private $exceptionListeners;
/**
* Constructor.
*
* @param FirewallMapInterface $map A FirewallMapInterface instance
* @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance
*/
public function __construct(FirewallMapInterface $map, EventDispatcherInterface $dispatcher)
{
$this->map = $map;
$this->dispatcher = $dispatcher;
$this->exceptionListeners = new \SplObjectStorage();
}
/**
* Handles security.
*
* @param GetResponseEvent $event An GetResponseEvent instance
*/
public function onKernelRequest(GetResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
// register listeners for this firewall
list($listeners, $exceptionListener) = $this->map->getListeners($event->getRequest());
if (null !== $exceptionListener) {
$this->exceptionListeners[$event->getRequest()] = $exceptionListener;
$exceptionListener->register($this->dispatcher);
}
// initiate the listener chain
foreach ($listeners as $listener) {
$listener->handle($event);
if ($event->hasResponse()) {
break;
}
}
}
public function onKernelFinishRequest(FinishRequestEvent $event)
{
$request = $event->getRequest();
if (isset($this->exceptionListeners[$request])) {
$this->exceptionListeners[$request]->unregister($this->dispatcher);
unset($this->exceptionListeners[$request]);
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(
KernelEvents::REQUEST => array('onKernelRequest', 8),
KernelEvents::FINISH_REQUEST => 'onKernelFinishRequest',
);
}
}

View File

@@ -0,0 +1,242 @@
<?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 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\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\SessionUnavailableException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\Security\Http\HttpUtils;
/**
* The AbstractAuthenticationListener is the preferred base class for all
* browser-/HTTP-based authentication requests.
*
* Subclasses likely have to implement the following:
* - an TokenInterface to hold authentication related data
* - an AuthenticationProvider to perform the actual authentication of the
* token, retrieve the UserInterface implementation from a database, and
* perform the specific account checks using the UserChecker
*
* By default, this listener only is active for a specific path, e.g.
* /login_check. If you want to change this behavior, you can overwrite the
* requiresAuthentication() method.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class AbstractAuthenticationListener implements ListenerInterface
{
protected $options;
protected $logger;
protected $authenticationManager;
protected $providerKey;
protected $httpUtils;
private $tokenStorage;
private $sessionStrategy;
private $dispatcher;
private $successHandler;
private $failureHandler;
private $rememberMeServices;
/**
* Constructor.
*
* @param TokenStorageInterface $tokenStorage A TokenStorageInterface instance
* @param AuthenticationManagerInterface $authenticationManager An AuthenticationManagerInterface instance
* @param SessionAuthenticationStrategyInterface $sessionStrategy
* @param HttpUtils $httpUtils An HttpUtils instance
* @param string $providerKey
* @param AuthenticationSuccessHandlerInterface $successHandler
* @param AuthenticationFailureHandlerInterface $failureHandler
* @param array $options An array of options for the processing of a
* successful, or failed authentication attempt
* @param LoggerInterface|null $logger A LoggerInterface instance
* @param EventDispatcherInterface|null $dispatcher An EventDispatcherInterface instance
*
* @throws \InvalidArgumentException
*/
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, HttpUtils $httpUtils, $providerKey, AuthenticationSuccessHandlerInterface $successHandler, AuthenticationFailureHandlerInterface $failureHandler, array $options = array(), LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->sessionStrategy = $sessionStrategy;
$this->providerKey = $providerKey;
$this->successHandler = $successHandler;
$this->failureHandler = $failureHandler;
$this->options = array_merge(array(
'check_path' => '/login_check',
'login_path' => '/login',
'always_use_default_target_path' => false,
'default_target_path' => '/',
'target_path_parameter' => '_target_path',
'use_referer' => false,
'failure_path' => null,
'failure_forward' => false,
'require_previous_session' => true,
), $options);
$this->logger = $logger;
$this->dispatcher = $dispatcher;
$this->httpUtils = $httpUtils;
}
/**
* Sets the RememberMeServices implementation to use.
*
* @param RememberMeServicesInterface $rememberMeServices
*/
public function setRememberMeServices(RememberMeServicesInterface $rememberMeServices)
{
$this->rememberMeServices = $rememberMeServices;
}
/**
* Handles form based authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*
* @throws \RuntimeException
* @throws SessionUnavailableException
*/
final public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$this->requiresAuthentication($request)) {
return;
}
if (!$request->hasSession()) {
throw new \RuntimeException('This authentication method requires a session.');
}
try {
if ($this->options['require_previous_session'] && !$request->hasPreviousSession()) {
throw new SessionUnavailableException('Your session has timed out, or you have disabled cookies.');
}
if (null === $returnValue = $this->attemptAuthentication($request)) {
return;
}
if ($returnValue instanceof TokenInterface) {
$this->sessionStrategy->onAuthentication($request, $returnValue);
$response = $this->onSuccess($request, $returnValue);
} elseif ($returnValue instanceof Response) {
$response = $returnValue;
} else {
throw new \RuntimeException('attemptAuthentication() must either return a Response, an implementation of TokenInterface, or null.');
}
} catch (AuthenticationException $e) {
$response = $this->onFailure($request, $e);
}
$event->setResponse($response);
}
/**
* Whether this request requires authentication.
*
* The default implementation only processes requests to a specific path,
* but a subclass could change this to only authenticate requests where a
* certain parameters is present.
*
* @param Request $request
*
* @return bool
*/
protected function requiresAuthentication(Request $request)
{
return $this->httpUtils->checkRequestPath($request, $this->options['check_path']);
}
/**
* Performs authentication.
*
* @param Request $request A Request instance
*
* @return TokenInterface|Response|null The authenticated token, null if full authentication is not possible, or a Response
*
* @throws AuthenticationException if the authentication fails
*/
abstract protected function attemptAuthentication(Request $request);
private function onFailure(Request $request, AuthenticationException $failed)
{
if (null !== $this->logger) {
$this->logger->info('Authentication request failed.', array('exception' => $failed));
}
$token = $this->tokenStorage->getToken();
if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
$this->tokenStorage->setToken(null);
}
$response = $this->failureHandler->onAuthenticationFailure($request, $failed);
if (!$response instanceof Response) {
throw new \RuntimeException('Authentication Failure Handler did not return a Response.');
}
return $response;
}
private function onSuccess(Request $request, TokenInterface $token)
{
if (null !== $this->logger) {
$this->logger->info('User has been authenticated successfully.', array('username' => $token->getUsername()));
}
$this->tokenStorage->setToken($token);
$session = $request->getSession();
$session->remove(Security::AUTHENTICATION_ERROR);
$session->remove(Security::LAST_USERNAME);
if (null !== $this->dispatcher) {
$loginEvent = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
}
$response = $this->successHandler->onAuthenticationSuccess($request, $token);
if (!$response instanceof Response) {
throw new \RuntimeException('Authentication Success Handler did not return a Response.');
}
if (null !== $this->rememberMeServices) {
$this->rememberMeServices->loginSuccess($request, $response, $token);
}
return $response;
}
}

View File

@@ -0,0 +1,123 @@
<?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 Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
/**
* AbstractPreAuthenticatedListener is the base class for all listener that
* authenticates users based on a pre-authenticated request (like a certificate
* for instance).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
abstract class AbstractPreAuthenticatedListener implements ListenerInterface
{
protected $logger;
private $tokenStorage;
private $authenticationManager;
private $providerKey;
private $dispatcher;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, $providerKey, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null)
{
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->providerKey = $providerKey;
$this->logger = $logger;
$this->dispatcher = $dispatcher;
}
/**
* Handles pre-authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
final public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
try {
list($user, $credentials) = $this->getPreAuthenticatedData($request);
} catch (BadCredentialsException $e) {
$this->clearToken($e);
return;
}
if (null !== $this->logger) {
$this->logger->debug('Checking current security token.', array('token' => (string) $this->tokenStorage->getToken()));
}
if (null !== $token = $this->tokenStorage->getToken()) {
if ($token instanceof PreAuthenticatedToken && $this->providerKey == $token->getProviderKey() && $token->isAuthenticated() && $token->getUsername() === $user) {
return;
}
}
if (null !== $this->logger) {
$this->logger->debug('Trying to pre-authenticate user.', array('username' => (string) $user));
}
try {
$token = $this->authenticationManager->authenticate(new PreAuthenticatedToken($user, $credentials, $this->providerKey));
if (null !== $this->logger) {
$this->logger->info('Pre-authentication successful.', array('token' => (string) $token));
}
$this->tokenStorage->setToken($token);
if (null !== $this->dispatcher) {
$loginEvent = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
}
} catch (AuthenticationException $e) {
$this->clearToken($e);
}
}
/**
* Clears a PreAuthenticatedToken for this provider (if present).
*
* @param AuthenticationException $exception
*/
private function clearToken(AuthenticationException $exception)
{
$token = $this->tokenStorage->getToken();
if ($token instanceof PreAuthenticatedToken && $this->providerKey === $token->getProviderKey()) {
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info('Cleared security token due to an exception.', array('exception' => $exception));
}
}
}
/**
* Gets the user and credentials from the Request.
*
* @param Request $request A Request instance
*
* @return array An array composed of the user and the credentials
*/
abstract protected function getPreAuthenticatedData(Request $request);
}

View File

@@ -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\Component\Security\Http\Firewall;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Symfony\Component\Security\Http\AccessMapInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
/**
* AccessListener enforces access control rules.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AccessListener implements ListenerInterface
{
private $tokenStorage;
private $accessDecisionManager;
private $map;
private $authManager;
public function __construct(TokenStorageInterface $tokenStorage, AccessDecisionManagerInterface $accessDecisionManager, AccessMapInterface $map, AuthenticationManagerInterface $authManager)
{
$this->tokenStorage = $tokenStorage;
$this->accessDecisionManager = $accessDecisionManager;
$this->map = $map;
$this->authManager = $authManager;
}
/**
* Handles access authorization.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*
* @throws AccessDeniedException
* @throws AuthenticationCredentialsNotFoundException
*/
public function handle(GetResponseEvent $event)
{
if (null === $token = $this->tokenStorage->getToken()) {
throw new AuthenticationCredentialsNotFoundException('A Token was not found in the TokenStorage.');
}
$request = $event->getRequest();
list($attributes) = $this->map->getPatterns($request);
if (null === $attributes) {
return;
}
if (!$token->isAuthenticated()) {
$token = $this->authManager->authenticate($token);
$this->tokenStorage->setToken($token);
}
if (!$this->accessDecisionManager->decide($token, $attributes, $request)) {
$exception = new AccessDeniedException();
$exception->setAttributes($attributes);
$exception->setSubject($request);
throw $exception;
}
}
}

View File

@@ -0,0 +1,70 @@
<?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 Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
/**
* AnonymousAuthenticationListener automatically adds a Token if none is
* already present.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class AnonymousAuthenticationListener implements ListenerInterface
{
private $tokenStorage;
private $secret;
private $authenticationManager;
private $logger;
public function __construct(TokenStorageInterface $tokenStorage, $secret, LoggerInterface $logger = null, AuthenticationManagerInterface $authenticationManager = null)
{
$this->tokenStorage = $tokenStorage;
$this->secret = $secret;
$this->authenticationManager = $authenticationManager;
$this->logger = $logger;
}
/**
* Handles anonymous authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
if (null !== $this->tokenStorage->getToken()) {
return;
}
try {
$token = new AnonymousToken($this->secret, 'anon.', array());
if (null !== $this->authenticationManager) {
$token = $this->authenticationManager->authenticate($token);
}
$this->tokenStorage->setToken($token);
if (null !== $this->logger) {
$this->logger->info('Populated the TokenStorage with an anonymous Token.');
}
} catch (AuthenticationException $failed) {
if (null !== $this->logger) {
$this->logger->info('Anonymous authentication failed.', array('exception' => $failed));
}
}
}
}

View File

@@ -0,0 +1,93 @@
<?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 Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* BasicAuthenticationListener implements Basic HTTP authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class BasicAuthenticationListener implements ListenerInterface
{
private $tokenStorage;
private $authenticationManager;
private $providerKey;
private $authenticationEntryPoint;
private $logger;
private $ignoreFailure;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint, LoggerInterface $logger = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->tokenStorage = $tokenStorage;
$this->authenticationManager = $authenticationManager;
$this->providerKey = $providerKey;
$this->authenticationEntryPoint = $authenticationEntryPoint;
$this->logger = $logger;
$this->ignoreFailure = false;
}
/**
* Handles basic authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (null === $username = $request->headers->get('PHP_AUTH_USER')) {
return;
}
if (null !== $token = $this->tokenStorage->getToken()) {
if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $username) {
return;
}
}
if (null !== $this->logger) {
$this->logger->info('Basic authentication Authorization header found for user.', array('username' => $username));
}
try {
$token = $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $request->headers->get('PHP_AUTH_PW'), $this->providerKey));
$this->tokenStorage->setToken($token);
} catch (AuthenticationException $e) {
$token = $this->tokenStorage->getToken();
if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
$this->tokenStorage->setToken(null);
}
if (null !== $this->logger) {
$this->logger->info('Basic authentication failed for user.', array('username' => $username, 'exception' => $e));
}
if ($this->ignoreFailure) {
return;
}
$event->setResponse($this->authenticationEntryPoint->start($request, $e));
}
}
}

View File

@@ -0,0 +1,71 @@
<?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 Symfony\Component\Security\Http\AccessMapInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
/**
* ChannelListener switches the HTTP protocol based on the access control
* configuration.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ChannelListener implements ListenerInterface
{
private $map;
private $authenticationEntryPoint;
private $logger;
public function __construct(AccessMapInterface $map, AuthenticationEntryPointInterface $authenticationEntryPoint, LoggerInterface $logger = null)
{
$this->map = $map;
$this->authenticationEntryPoint = $authenticationEntryPoint;
$this->logger = $logger;
}
/**
* Handles channel management.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
list(, $channel) = $this->map->getPatterns($request);
if ('https' === $channel && !$request->isSecure()) {
if (null !== $this->logger) {
$this->logger->info('Redirecting to HTTPS.');
}
$response = $this->authenticationEntryPoint->start($request);
$event->setResponse($response);
return;
}
if ('http' === $channel && $request->isSecure()) {
if (null !== $this->logger) {
$this->logger->info('Redirecting to HTTP.');
}
$response = $this->authenticationEntryPoint->start($request);
$event->setResponse($response);
}
}
}

View File

@@ -0,0 +1,187 @@
<?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\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
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\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* ContextListener manages the SecurityContext persistence through a session.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class ContextListener implements ListenerInterface
{
private $tokenStorage;
private $contextKey;
private $sessionKey;
private $logger;
private $userProviders;
private $dispatcher;
private $registered;
private $trustResolver;
public function __construct(TokenStorageInterface $tokenStorage, array $userProviders, $contextKey, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null, AuthenticationTrustResolverInterface $trustResolver = null)
{
if (empty($contextKey)) {
throw new \InvalidArgumentException('$contextKey must not be empty.');
}
foreach ($userProviders as $userProvider) {
if (!$userProvider instanceof UserProviderInterface) {
throw new \InvalidArgumentException(sprintf('User provider "%s" must implement "Symfony\Component\Security\Core\User\UserProviderInterface".', get_class($userProvider)));
}
}
$this->tokenStorage = $tokenStorage;
$this->userProviders = $userProviders;
$this->contextKey = $contextKey;
$this->sessionKey = '_security_'.$contextKey;
$this->logger = $logger;
$this->dispatcher = $dispatcher;
$this->trustResolver = $trustResolver ?: new AuthenticationTrustResolver(AnonymousToken::class, RememberMeToken::class);
}
/**
* Reads the Security Token from the session.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
if (!$this->registered && null !== $this->dispatcher && $event->isMasterRequest()) {
$this->dispatcher->addListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
$this->registered = true;
}
$request = $event->getRequest();
$session = $request->hasPreviousSession() ? $request->getSession() : null;
if (null === $session || null === $token = $session->get($this->sessionKey)) {
$this->tokenStorage->setToken(null);
return;
}
$token = unserialize($token);
if (null !== $this->logger) {
$this->logger->debug('Read existing security token from the session.', array('key' => $this->sessionKey));
}
if ($token instanceof TokenInterface) {
$token = $this->refreshUser($token);
} elseif (null !== $token) {
if (null !== $this->logger) {
$this->logger->warning('Expected a security token from the session, got something else.', array('key' => $this->sessionKey, 'received' => $token));
}
$token = null;
}
$this->tokenStorage->setToken($token);
}
/**
* Writes the security token into the session.
*
* @param FilterResponseEvent $event A FilterResponseEvent instance
*/
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
if (!$event->getRequest()->hasSession()) {
return;
}
$this->dispatcher->removeListener(KernelEvents::RESPONSE, array($this, 'onKernelResponse'));
$this->registered = false;
$request = $event->getRequest();
$session = $request->getSession();
if ((null === $token = $this->tokenStorage->getToken()) || $this->trustResolver->isAnonymous($token)) {
if ($request->hasPreviousSession()) {
$session->remove($this->sessionKey);
}
} else {
$session->set($this->sessionKey, serialize($token));
if (null !== $this->logger) {
$this->logger->debug('Stored the security token in the session.', array('key' => $this->sessionKey));
}
}
}
/**
* Refreshes the user by reloading it from the user provider.
*
* @param TokenInterface $token
*
* @return TokenInterface|null
*
* @throws \RuntimeException
*/
protected function refreshUser(TokenInterface $token)
{
$user = $token->getUser();
if (!$user instanceof UserInterface) {
return $token;
}
$userNotFoundByProvider = false;
foreach ($this->userProviders as $provider) {
try {
$refreshedUser = $provider->refreshUser($user);
$token->setUser($refreshedUser);
if (null !== $this->logger) {
$this->logger->debug('User was reloaded from a user provider.', array('username' => $refreshedUser->getUsername(), 'provider' => get_class($provider)));
}
return $token;
} catch (UnsupportedUserException $e) {
// let's try the next user provider
} catch (UsernameNotFoundException $e) {
if (null !== $this->logger) {
$this->logger->warning('Username could not be found in the selected user provider.', array('username' => $e->getUsername(), 'provider' => get_class($provider)));
}
$userNotFoundByProvider = true;
}
}
if ($userNotFoundByProvider) {
return;
}
throw new \RuntimeException(sprintf('There is no user provider for user "%s".', get_class($user)));
}
}

View File

@@ -0,0 +1,219 @@
<?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 Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\AuthenticationServiceException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
/**
* DigestAuthenticationListener implements Digest HTTP authentication.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class DigestAuthenticationListener implements ListenerInterface
{
private $tokenStorage;
private $provider;
private $providerKey;
private $authenticationEntryPoint;
private $logger;
public function __construct(TokenStorageInterface $tokenStorage, UserProviderInterface $provider, $providerKey, DigestAuthenticationEntryPoint $authenticationEntryPoint, LoggerInterface $logger = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->tokenStorage = $tokenStorage;
$this->provider = $provider;
$this->providerKey = $providerKey;
$this->authenticationEntryPoint = $authenticationEntryPoint;
$this->logger = $logger;
}
/**
* Handles digest authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*
* @throws AuthenticationServiceException
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$header = $request->server->get('PHP_AUTH_DIGEST')) {
return;
}
$digestAuth = new DigestData($header);
if (null !== $token = $this->tokenStorage->getToken()) {
if ($token instanceof UsernamePasswordToken && $token->isAuthenticated() && $token->getUsername() === $digestAuth->getUsername()) {
return;
}
}
if (null !== $this->logger) {
$this->logger->debug('Digest Authorization header received from user agent.', array('header' => $header));
}
try {
$digestAuth->validateAndDecode($this->authenticationEntryPoint->getSecret(), $this->authenticationEntryPoint->getRealmName());
} catch (BadCredentialsException $e) {
$this->fail($event, $request, $e);
return;
}
try {
$user = $this->provider->loadUserByUsername($digestAuth->getUsername());
if (null === $user) {
throw new AuthenticationServiceException('Digest User provider returned null, which is an interface contract violation');
}
$serverDigestMd5 = $digestAuth->calculateServerDigest($user->getPassword(), $request->getMethod());
} catch (UsernameNotFoundException $e) {
$this->fail($event, $request, new BadCredentialsException(sprintf('Username %s not found.', $digestAuth->getUsername())));
return;
}
if (!hash_equals($serverDigestMd5, $digestAuth->getResponse())) {
if (null !== $this->logger) {
$this->logger->debug('Unexpected response from the DigestAuth received; is the header returning a clear text passwords?', array('expected' => $serverDigestMd5, 'received' => $digestAuth->getResponse()));
}
$this->fail($event, $request, new BadCredentialsException('Incorrect response'));
return;
}
if ($digestAuth->isNonceExpired()) {
$this->fail($event, $request, new NonceExpiredException('Nonce has expired/timed out.'));
return;
}
if (null !== $this->logger) {
$this->logger->info('Digest authentication successful.', array('username' => $digestAuth->getUsername(), 'received' => $digestAuth->getResponse()));
}
$this->tokenStorage->setToken(new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey));
}
private function fail(GetResponseEvent $event, Request $request, AuthenticationException $authException)
{
$token = $this->tokenStorage->getToken();
if ($token instanceof UsernamePasswordToken && $this->providerKey === $token->getProviderKey()) {
$this->tokenStorage->setToken(null);
}
if (null !== $this->logger) {
$this->logger->info('Digest authentication failed.', array('exception' => $authException));
}
$event->setResponse($this->authenticationEntryPoint->start($request, $authException));
}
}
class DigestData
{
private $elements = array();
private $header;
private $nonceExpiryTime;
public function __construct($header)
{
$this->header = $header;
preg_match_all('/(\w+)=("((?:[^"\\\\]|\\\\.)+)"|([^\s,$]+))/', $header, $matches, PREG_SET_ORDER);
foreach ($matches as $match) {
if (isset($match[1]) && isset($match[3])) {
$this->elements[$match[1]] = isset($match[4]) ? $match[4] : $match[3];
}
}
}
public function getResponse()
{
return $this->elements['response'];
}
public function getUsername()
{
return strtr($this->elements['username'], array('\\"' => '"', '\\\\' => '\\'));
}
public function validateAndDecode($entryPointKey, $expectedRealm)
{
if ($keys = array_diff(array('username', 'realm', 'nonce', 'uri', 'response'), array_keys($this->elements))) {
throw new BadCredentialsException(sprintf('Missing mandatory digest value; received header "%s" (%s)', $this->header, implode(', ', $keys)));
}
if ('auth' === $this->elements['qop'] && !isset($this->elements['nc'], $this->elements['cnonce'])) {
throw new BadCredentialsException(sprintf('Missing mandatory digest value; received header "%s"', $this->header));
}
if ($expectedRealm !== $this->elements['realm']) {
throw new BadCredentialsException(sprintf('Response realm name "%s" does not match system realm name of "%s".', $this->elements['realm'], $expectedRealm));
}
if (false === $nonceAsPlainText = base64_decode($this->elements['nonce'])) {
throw new BadCredentialsException(sprintf('Nonce is not encoded in Base64; received nonce "%s".', $this->elements['nonce']));
}
$nonceTokens = explode(':', $nonceAsPlainText);
if (2 !== count($nonceTokens)) {
throw new BadCredentialsException(sprintf('Nonce should have yielded two tokens but was "%s".', $nonceAsPlainText));
}
$this->nonceExpiryTime = $nonceTokens[0];
if (md5($this->nonceExpiryTime.':'.$entryPointKey) !== $nonceTokens[1]) {
throw new BadCredentialsException(sprintf('Nonce token compromised "%s".', $nonceAsPlainText));
}
}
public function calculateServerDigest($password, $httpMethod)
{
$a2Md5 = md5(strtoupper($httpMethod).':'.$this->elements['uri']);
$a1Md5 = md5($this->elements['username'].':'.$this->elements['realm'].':'.$password);
$digest = $a1Md5.':'.$this->elements['nonce'];
if (!isset($this->elements['qop'])) {
} elseif ('auth' === $this->elements['qop']) {
$digest .= ':'.$this->elements['nc'].':'.$this->elements['cnonce'].':'.$this->elements['qop'];
} else {
throw new \InvalidArgumentException(sprintf('This method does not support a qop: "%s".', $this->elements['qop']));
}
$digest .= ':'.$a2Md5;
return md5($digest);
}
public function isNonceExpired()
{
return $this->nonceExpiryTime < microtime(true);
}
}

View File

@@ -0,0 +1,227 @@
<?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 Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Core\Exception\AccountStatusException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\InsufficientAuthenticationException;
use Symfony\Component\Security\Core\Exception\LogoutException;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\HttpFoundation\Request;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* ExceptionListener catches authentication exception and converts them to
* Response instances.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class ExceptionListener
{
use TargetPathTrait;
private $tokenStorage;
private $providerKey;
private $accessDeniedHandler;
private $authenticationEntryPoint;
private $authenticationTrustResolver;
private $errorPage;
private $logger;
private $httpUtils;
private $stateless;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationTrustResolverInterface $trustResolver, HttpUtils $httpUtils, $providerKey, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null, LoggerInterface $logger = null, $stateless = false)
{
$this->tokenStorage = $tokenStorage;
$this->accessDeniedHandler = $accessDeniedHandler;
$this->httpUtils = $httpUtils;
$this->providerKey = $providerKey;
$this->authenticationEntryPoint = $authenticationEntryPoint;
$this->authenticationTrustResolver = $trustResolver;
$this->errorPage = $errorPage;
$this->logger = $logger;
$this->stateless = $stateless;
}
/**
* Registers a onKernelException listener to take care of security exceptions.
*
* @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance
*/
public function register(EventDispatcherInterface $dispatcher)
{
$dispatcher->addListener(KernelEvents::EXCEPTION, array($this, 'onKernelException'));
}
/**
* Unregisters the dispatcher.
*
* @param EventDispatcherInterface $dispatcher An EventDispatcherInterface instance
*/
public function unregister(EventDispatcherInterface $dispatcher)
{
$dispatcher->removeListener(KernelEvents::EXCEPTION, array($this, 'onKernelException'));
}
/**
* Handles security related exceptions.
*
* @param GetResponseForExceptionEvent $event An GetResponseForExceptionEvent instance
*/
public function onKernelException(GetResponseForExceptionEvent $event)
{
$exception = $event->getException();
do {
if ($exception instanceof AuthenticationException) {
return $this->handleAuthenticationException($event, $exception);
} elseif ($exception instanceof AccessDeniedException) {
return $this->handleAccessDeniedException($event, $exception);
} elseif ($exception instanceof LogoutException) {
return $this->handleLogoutException($exception);
}
} while (null !== $exception = $exception->getPrevious());
}
private function handleAuthenticationException(GetResponseForExceptionEvent $event, AuthenticationException $exception)
{
if (null !== $this->logger) {
$this->logger->info('An AuthenticationException was thrown; redirecting to authentication entry point.', array('exception' => $exception));
}
try {
$event->setResponse($this->startAuthentication($event->getRequest(), $exception));
} catch (\Exception $e) {
$event->setException($e);
}
}
private function handleAccessDeniedException(GetResponseForExceptionEvent $event, AccessDeniedException $exception)
{
$event->setException(new AccessDeniedHttpException($exception->getMessage(), $exception));
$token = $this->tokenStorage->getToken();
if (!$this->authenticationTrustResolver->isFullFledged($token)) {
if (null !== $this->logger) {
$this->logger->debug('Access denied, the user is not fully authenticated; redirecting to authentication entry point.', array('exception' => $exception));
}
try {
$insufficientAuthenticationException = new InsufficientAuthenticationException('Full authentication is required to access this resource.', 0, $exception);
$insufficientAuthenticationException->setToken($token);
$event->setResponse($this->startAuthentication($event->getRequest(), $insufficientAuthenticationException));
} catch (\Exception $e) {
$event->setException($e);
}
return;
}
if (null !== $this->logger) {
$this->logger->debug('Access denied, the user is neither anonymous, nor remember-me.', array('exception' => $exception));
}
try {
if (null !== $this->accessDeniedHandler) {
$response = $this->accessDeniedHandler->handle($event->getRequest(), $exception);
if ($response instanceof Response) {
$event->setResponse($response);
}
} elseif (null !== $this->errorPage) {
$subRequest = $this->httpUtils->createRequest($event->getRequest(), $this->errorPage);
$subRequest->attributes->set(Security::ACCESS_DENIED_ERROR, $exception);
$event->setResponse($event->getKernel()->handle($subRequest, HttpKernelInterface::SUB_REQUEST, true));
}
} catch (\Exception $e) {
if (null !== $this->logger) {
$this->logger->error('An exception was thrown when handling an AccessDeniedException.', array('exception' => $e));
}
$event->setException(new \RuntimeException('Exception thrown when handling an exception.', 0, $e));
}
}
private function handleLogoutException(LogoutException $exception)
{
if (null !== $this->logger) {
$this->logger->info('A LogoutException was thrown.', array('exception' => $exception));
}
}
/**
* @param Request $request
* @param AuthenticationException $authException
*
* @return Response
*
* @throws AuthenticationException
*/
private function startAuthentication(Request $request, AuthenticationException $authException)
{
if (null === $this->authenticationEntryPoint) {
throw $authException;
}
if (null !== $this->logger) {
$this->logger->debug('Calling Authentication entry point.');
}
if (!$this->stateless) {
$this->setTargetPath($request);
}
if ($authException instanceof AccountStatusException) {
// remove the security token to prevent infinite redirect loops
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info('The security token was removed due to an AccountStatusException.', array('exception' => $authException));
}
}
$response = $this->authenticationEntryPoint->start($request, $authException);
if (!$response instanceof Response) {
$given = is_object($response) ? get_class($response) : gettype($response);
throw new \LogicException(sprintf('The %s::start() method must return a Response object (%s returned)', get_class($this->authenticationEntryPoint), $given));
}
return $response;
}
/**
* @param Request $request
*/
protected function setTargetPath(Request $request)
{
// session isn't required when using HTTP basic authentication mechanism for example
if ($request->hasSession() && $request->isMethodSafe(false) && !$request->isXmlHttpRequest()) {
$this->saveTargetPath($request->getSession(), $this->providerKey, $request->getUri());
}
}
}

View File

@@ -0,0 +1,29 @@
<?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 Symfony\Component\HttpKernel\Event\GetResponseEvent;
/**
* Interface that must be implemented by firewall listeners.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface ListenerInterface
{
/**
* This interface must be implemented by firewall listeners.
*
* @param GetResponseEvent $event
*/
public function handle(GetResponseEvent $event);
}

View File

@@ -0,0 +1,132 @@
<?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 Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\LogoutException;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Http\ParameterBagUtils;
/**
* LogoutListener logout users.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class LogoutListener implements ListenerInterface
{
private $tokenStorage;
private $options;
private $handlers;
private $successHandler;
private $httpUtils;
private $csrfTokenManager;
/**
* Constructor.
*
* @param TokenStorageInterface $tokenStorage
* @param HttpUtils $httpUtils An HttpUtils instance
* @param LogoutSuccessHandlerInterface $successHandler A LogoutSuccessHandlerInterface instance
* @param array $options An array of options to process a logout attempt
* @param CsrfTokenManagerInterface|null $csrfTokenManager A CsrfTokenManagerInterface instance
*/
public function __construct(TokenStorageInterface $tokenStorage, HttpUtils $httpUtils, LogoutSuccessHandlerInterface $successHandler, array $options = array(), CsrfTokenManagerInterface $csrfTokenManager = null)
{
$this->tokenStorage = $tokenStorage;
$this->httpUtils = $httpUtils;
$this->options = array_merge(array(
'csrf_parameter' => '_csrf_token',
'csrf_token_id' => 'logout',
'logout_path' => '/logout',
), $options);
$this->successHandler = $successHandler;
$this->csrfTokenManager = $csrfTokenManager;
$this->handlers = array();
}
/**
* Adds a logout handler.
*
* @param LogoutHandlerInterface $handler
*/
public function addHandler(LogoutHandlerInterface $handler)
{
$this->handlers[] = $handler;
}
/**
* Performs the logout if requested.
*
* If a CsrfTokenManagerInterface instance is available, it will be used to
* validate the request.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*
* @throws LogoutException if the CSRF token is invalid
* @throws \RuntimeException if the LogoutSuccessHandlerInterface instance does not return a response
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$this->requiresLogout($request)) {
return;
}
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 LogoutException('Invalid CSRF token.');
}
}
$response = $this->successHandler->onLogoutSuccess($request);
if (!$response instanceof Response) {
throw new \RuntimeException('Logout Success Handler did not return a Response.');
}
// handle multiple logout attempts gracefully
if ($token = $this->tokenStorage->getToken()) {
foreach ($this->handlers as $handler) {
$handler->logout($request, $response, $token);
}
}
$this->tokenStorage->setToken(null);
$event->setResponse($response);
}
/**
* Whether this request is asking for logout.
*
* The default implementation only processed requests to a specific path,
* but a subclass could change this to logout requests where
* certain parameters is present.
*
* @param Request $request
*
* @return bool
*/
protected function requiresLogout(Request $request)
{
return isset($this->options['logout_path']) && $this->httpUtils->checkRequestPath($request, $this->options['logout_path']);
}
}

View File

@@ -0,0 +1,110 @@
<?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\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;
/**
* RememberMeListener implements authentication capabilities via a cookie.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class RememberMeListener implements ListenerInterface
{
private $tokenStorage;
private $rememberMeServices;
private $authenticationManager;
private $logger;
private $dispatcher;
private $catchExceptions = true;
private $sessionStrategy;
/**
* Constructor.
*
* @param TokenStorageInterface $tokenStorage
* @param RememberMeServicesInterface $rememberMeServices
* @param AuthenticationManagerInterface $authenticationManager
* @param LoggerInterface|null $logger
* @param EventDispatcherInterface|null $dispatcher
* @param bool $catchExceptions
* @param SessionAuthenticationStrategyInterface|null $sessionStrategy
*/
public function __construct(TokenStorageInterface $tokenStorage, RememberMeServicesInterface $rememberMeServices, AuthenticationManagerInterface $authenticationManager, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null, $catchExceptions = true, SessionAuthenticationStrategyInterface $sessionStrategy = null)
{
$this->tokenStorage = $tokenStorage;
$this->rememberMeServices = $rememberMeServices;
$this->authenticationManager = $authenticationManager;
$this->logger = $logger;
$this->dispatcher = $dispatcher;
$this->catchExceptions = $catchExceptions;
$this->sessionStrategy = null === $sessionStrategy ? new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE) : $sessionStrategy;
}
/**
* Handles remember-me cookie based authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
if (null !== $this->tokenStorage->getToken()) {
return;
}
$request = $event->getRequest();
if (null === $token = $this->rememberMeServices->autoLogin($request)) {
return;
}
try {
$token = $this->authenticationManager->authenticate($token);
if ($request->hasSession() && $request->getSession()->isStarted()) {
$this->sessionStrategy->onAuthentication($request, $token);
}
$this->tokenStorage->setToken($token);
if (null !== $this->dispatcher) {
$loginEvent = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
}
if (null !== $this->logger) {
$this->logger->debug('Populated the token storage with a remember-me token.');
}
} catch (AuthenticationException $e) {
if (null !== $this->logger) {
$this->logger->warning(
'The token storage was not populated with remember-me token as the'
.' AuthenticationManager rejected the AuthenticationToken returned'
.' by the RememberMeServices.', array('exception' => $e)
);
}
$this->rememberMeServices->loginFail($request);
if (!$this->catchExceptions) {
throw $e;
}
}
}
}

View File

@@ -0,0 +1,49 @@
<?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 Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* REMOTE_USER authentication listener.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Maxime Douailin <maxime.douailin@gmail.com>
*/
class RemoteUserAuthenticationListener extends AbstractPreAuthenticatedListener
{
private $userKey;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, $providerKey, $userKey = 'REMOTE_USER', LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null)
{
parent::__construct($tokenStorage, $authenticationManager, $providerKey, $logger, $dispatcher);
$this->userKey = $userKey;
}
/**
* {@inheritdoc}
*/
protected function getPreAuthenticatedData(Request $request)
{
if (!$request->server->has($this->userKey)) {
throw new BadCredentialsException(sprintf('User key was not found: %s', $this->userKey));
}
return array($request->server->get($this->userKey), null);
}
}

View File

@@ -0,0 +1,121 @@
<?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 Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
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\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Http\Authentication\SimpleFormAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Http\ParameterBagUtils;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Psr\Log\LoggerInterface;
/**
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class SimpleFormAuthenticationListener extends AbstractAuthenticationListener
{
private $simpleAuthenticator;
private $csrfTokenManager;
/**
* Constructor.
*
* @param TokenStorageInterface $tokenStorage A TokenStorageInterface instance
* @param AuthenticationManagerInterface $authenticationManager An AuthenticationManagerInterface instance
* @param SessionAuthenticationStrategyInterface $sessionStrategy
* @param HttpUtils $httpUtils An HttpUtils instance
* @param string $providerKey
* @param AuthenticationSuccessHandlerInterface $successHandler
* @param AuthenticationFailureHandlerInterface $failureHandler
* @param array $options An array of options for the processing of a
* successful, or failed authentication attempt
* @param LoggerInterface|null $logger A LoggerInterface instance
* @param EventDispatcherInterface|null $dispatcher An EventDispatcherInterface instance
* @param CsrfTokenManagerInterface|null $csrfTokenManager A CsrfTokenManagerInterface instance
* @param SimpleFormAuthenticatorInterface|null $simpleAuthenticator A SimpleFormAuthenticatorInterface instance
*
* @throws \InvalidArgumentException In case no simple authenticator is provided
*/
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, HttpUtils $httpUtils, $providerKey, AuthenticationSuccessHandlerInterface $successHandler, AuthenticationFailureHandlerInterface $failureHandler, array $options = array(), 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(array(
'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 = trim(ParameterBagUtils::getParameterBagValue($request->request, $this->options['username_parameter']));
$password = ParameterBagUtils::getParameterBagValue($request->request, $this->options['password_parameter']);
} else {
$username = trim(ParameterBagUtils::getRequestParameterValue($request, $this->options['username_parameter']));
$password = ParameterBagUtils::getRequestParameterValue($request, $this->options['password_parameter']);
}
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

@@ -0,0 +1,126 @@
<?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 Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Authentication\SimplePreAuthenticatorInterface;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
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\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* SimplePreAuthenticationListener implements simple proxying to an authenticator.
*
* @author Jordi Boggiano <j.boggiano@seld.be>
*/
class SimplePreAuthenticationListener implements ListenerInterface
{
private $tokenStorage;
private $authenticationManager;
private $providerKey;
private $simpleAuthenticator;
private $logger;
private $dispatcher;
/**
* Constructor.
*
* @param TokenStorageInterface $tokenStorage A TokenStorageInterface instance
* @param AuthenticationManagerInterface $authenticationManager An AuthenticationManagerInterface instance
* @param string $providerKey
* @param SimplePreAuthenticatorInterface $simpleAuthenticator A SimplePreAuthenticatorInterface instance
* @param LoggerInterface|null $logger A LoggerInterface instance
* @param EventDispatcherInterface|null $dispatcher An EventDispatcherInterface instance
*/
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, $providerKey, SimplePreAuthenticatorInterface $simpleAuthenticator, LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = 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 = $dispatcher;
}
/**
* Handles basic authentication.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (null !== $this->logger) {
$this->logger->info('Attempting SimplePreAuthentication.', array('key' => $this->providerKey, 'authenticator' => get_class($this->simpleAuthenticator)));
}
if (null !== $this->tokenStorage->getToken() && !$this->tokenStorage->getToken() instanceof AnonymousToken) {
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->tokenStorage->setToken($token);
if (null !== $this->dispatcher) {
$loginEvent = new InteractiveLoginEvent($request, $token);
$this->dispatcher->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $loginEvent);
}
} catch (AuthenticationException $e) {
$this->tokenStorage->setToken(null);
if (null !== $this->logger) {
$this->logger->info('SimplePreAuthentication request failed.', array('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)));
}
}
}
}

View File

@@ -0,0 +1,194 @@
<?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 Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Core\User\UserCheckerInterface;
use Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\SecurityEvents;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* SwitchUserListener allows a user to impersonate another one temporarily
* (like the Unix su command).
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class SwitchUserListener implements ListenerInterface
{
private $tokenStorage;
private $provider;
private $userChecker;
private $providerKey;
private $accessDecisionManager;
private $usernameParameter;
private $role;
private $logger;
private $dispatcher;
public function __construct(TokenStorageInterface $tokenStorage, UserProviderInterface $provider, UserCheckerInterface $userChecker, $providerKey, AccessDecisionManagerInterface $accessDecisionManager, LoggerInterface $logger = null, $usernameParameter = '_switch_user', $role = 'ROLE_ALLOWED_TO_SWITCH', EventDispatcherInterface $dispatcher = null)
{
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
$this->tokenStorage = $tokenStorage;
$this->provider = $provider;
$this->userChecker = $userChecker;
$this->providerKey = $providerKey;
$this->accessDecisionManager = $accessDecisionManager;
$this->usernameParameter = $usernameParameter;
$this->role = $role;
$this->logger = $logger;
$this->dispatcher = $dispatcher;
}
/**
* Handles the switch to another user.
*
* @param GetResponseEvent $event A GetResponseEvent instance
*
* @throws \LogicException if switching to a user failed
*/
public function handle(GetResponseEvent $event)
{
$request = $event->getRequest();
if (!$request->get($this->usernameParameter)) {
return;
}
if ('_exit' === $request->get($this->usernameParameter)) {
$this->tokenStorage->setToken($this->attemptExitUser($request));
} else {
try {
$this->tokenStorage->setToken($this->attemptSwitchUser($request));
} catch (AuthenticationException $e) {
throw new \LogicException(sprintf('Switch User failed: "%s"', $e->getMessage()));
}
}
$request->query->remove($this->usernameParameter);
$request->server->set('QUERY_STRING', http_build_query($request->query->all()));
$response = new RedirectResponse($request->getUri(), 302);
$event->setResponse($response);
}
/**
* Attempts to switch to another user.
*
* @param Request $request A Request instance
*
* @return TokenInterface|null The new TokenInterface if successfully switched, null otherwise
*
* @throws \LogicException
* @throws AccessDeniedException
*/
private function attemptSwitchUser(Request $request)
{
$token = $this->tokenStorage->getToken();
$originalToken = $this->getOriginalToken($token);
if (false !== $originalToken) {
if ($token->getUsername() === $request->get($this->usernameParameter)) {
return $token;
}
throw new \LogicException(sprintf('You are already switched to "%s" user.', $token->getUsername()));
}
if (false === $this->accessDecisionManager->decide($token, array($this->role))) {
$exception = new AccessDeniedException();
$exception->setAttributes($this->role);
throw $exception;
}
$username = $request->get($this->usernameParameter);
if (null !== $this->logger) {
$this->logger->info('Attempting to switch to user.', array('username' => $username));
}
$user = $this->provider->loadUserByUsername($username);
$this->userChecker->checkPostAuth($user);
$roles = $user->getRoles();
$roles[] = new SwitchUserRole('ROLE_PREVIOUS_ADMIN', $this->tokenStorage->getToken());
$token = new UsernamePasswordToken($user, $user->getPassword(), $this->providerKey, $roles);
if (null !== $this->dispatcher) {
$switchEvent = new SwitchUserEvent($request, $token->getUser());
$this->dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent);
}
return $token;
}
/**
* Attempts to exit from an already switched user.
*
* @param Request $request A Request instance
*
* @return TokenInterface The original TokenInterface instance
*
* @throws AuthenticationCredentialsNotFoundException
*/
private function attemptExitUser(Request $request)
{
if (null === ($currentToken = $this->tokenStorage->getToken()) || false === $original = $this->getOriginalToken($currentToken)) {
throw new AuthenticationCredentialsNotFoundException('Could not find original Token object.');
}
if (null !== $this->dispatcher && $original->getUser() instanceof UserInterface) {
$user = $this->provider->refreshUser($original->getUser());
$switchEvent = new SwitchUserEvent($request, $user);
$this->dispatcher->dispatch(SecurityEvents::SWITCH_USER, $switchEvent);
}
return $original;
}
/**
* Gets the original Token from a switched one.
*
* @param TokenInterface $token A switched TokenInterface instance
*
* @return TokenInterface|false The original TokenInterface instance, false if the current TokenInterface is not switched
*/
private function getOriginalToken(TokenInterface $token)
{
foreach ($token->getRoles() as $role) {
if ($role instanceof SwitchUserRole) {
return $role->getSource();
}
}
return false;
}
}

View File

@@ -0,0 +1,95 @@
<?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 Symfony\Component\HttpFoundation\Request;
use Psr\Log\LoggerInterface;
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\ParameterBagUtils;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface;
use Symfony\Component\Security\Http\HttpUtils;
use Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* UsernamePasswordFormAuthenticationListener is the default implementation of
* an authentication via a simple form composed of a username and a password.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class UsernamePasswordFormAuthenticationListener extends AbstractAuthenticationListener
{
private $csrfTokenManager;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, SessionAuthenticationStrategyInterface $sessionStrategy, HttpUtils $httpUtils, $providerKey, AuthenticationSuccessHandlerInterface $successHandler, AuthenticationFailureHandlerInterface $failureHandler, array $options = array(), LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null, CsrfTokenManagerInterface $csrfTokenManager = null)
{
parent::__construct($tokenStorage, $authenticationManager, $sessionStrategy, $httpUtils, $providerKey, $successHandler, $failureHandler, array_merge(array(
'username_parameter' => '_username',
'password_parameter' => '_password',
'csrf_parameter' => '_csrf_token',
'csrf_token_id' => 'authenticate',
'post_only' => true,
), $options), $logger, $dispatcher);
$this->csrfTokenManager = $csrfTokenManager;
}
/**
* {@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 = trim(ParameterBagUtils::getParameterBagValue($request->request, $this->options['username_parameter']));
$password = ParameterBagUtils::getParameterBagValue($request->request, $this->options['password_parameter']);
} else {
$username = trim(ParameterBagUtils::getRequestParameterValue($request, $this->options['username_parameter']));
$password = ParameterBagUtils::getRequestParameterValue($request, $this->options['password_parameter']);
}
if (strlen($username) > Security::MAX_USERNAME_LENGTH) {
throw new BadCredentialsException('Invalid username.');
}
$request->getSession()->set(Security::LAST_USERNAME, $username);
return $this->authenticationManager->authenticate(new UsernamePasswordToken($username, $password, $this->providerKey));
}
}

View File

@@ -0,0 +1,57 @@
<?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 Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Psr\Log\LoggerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
/**
* X509 authentication listener.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class X509AuthenticationListener extends AbstractPreAuthenticatedListener
{
private $userKey;
private $credentialKey;
public function __construct(TokenStorageInterface $tokenStorage, AuthenticationManagerInterface $authenticationManager, $providerKey, $userKey = 'SSL_CLIENT_S_DN_Email', $credentialKey = 'SSL_CLIENT_S_DN', LoggerInterface $logger = null, EventDispatcherInterface $dispatcher = null)
{
parent::__construct($tokenStorage, $authenticationManager, $providerKey, $logger, $dispatcher);
$this->userKey = $userKey;
$this->credentialKey = $credentialKey;
}
/**
* {@inheritdoc}
*/
protected function getPreAuthenticatedData(Request $request)
{
$user = null;
if ($request->server->has($this->userKey)) {
$user = $request->server->get($this->userKey);
} elseif ($request->server->has($this->credentialKey) && preg_match('#/emailAddress=(.+\@.+\..+)(/|$)#', $request->server->get($this->credentialKey), $matches)) {
$user = $matches[1];
}
if (null === $user) {
throw new BadCredentialsException(sprintf('SSL credentials not found: %s, %s', $this->userKey, $this->credentialKey));
}
return array($user, $request->server->get($this->credentialKey, ''));
}
}

View File

@@ -0,0 +1,51 @@
<?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;
use Symfony\Component\HttpFoundation\RequestMatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
/**
* FirewallMap allows configuration of different firewalls for specific parts
* of the website.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class FirewallMap implements FirewallMapInterface
{
private $map = array();
/**
* @param RequestMatcherInterface $requestMatcher
* @param array $listeners
* @param ExceptionListener $exceptionListener
*/
public function add(RequestMatcherInterface $requestMatcher = null, array $listeners = array(), ExceptionListener $exceptionListener = null)
{
$this->map[] = array($requestMatcher, $listeners, $exceptionListener);
}
/**
* {@inheritdoc}
*/
public function getListeners(Request $request)
{
foreach ($this->map as $elements) {
if (null === $elements[0] || $elements[0]->matches($request)) {
return array($elements[1], $elements[2]);
}
}
return array(array(), null);
}
}

View File

@@ -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\Component\Security\Http;
use Symfony\Component\HttpFoundation\Request;
/**
* This interface must be implemented by firewall maps.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface FirewallMapInterface
{
/**
* Returns the authentication listeners, and the exception listener to use
* for the given request.
*
* If there are no authentication listeners, the first inner array must be
* empty.
*
* If there is no exception listener, the second element of the outer array
* must be null.
*
* @param Request $request
*
* @return array of the format array(array(AuthenticationListener), ExceptionListener)
*/
public function getListeners(Request $request);
}

View File

@@ -0,0 +1,165 @@
<?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;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Routing\Matcher\UrlMatcherInterface;
use Symfony\Component\Routing\Matcher\RequestMatcherInterface;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\Security;
/**
* Encapsulates the logic needed to create sub-requests, redirect the user, and match URLs.
*
* @author Fabien Potencier <fabien@symfony.com>
*/
class HttpUtils
{
private $urlGenerator;
private $urlMatcher;
private $domainRegexp;
/**
* Constructor.
*
* @param UrlGeneratorInterface $urlGenerator A UrlGeneratorInterface instance
* @param UrlMatcherInterface|RequestMatcherInterface $urlMatcher The URL or Request matcher
* @param string|null $domainRegexp A regexp that the target of HTTP redirections must match, scheme included
*
* @throws \InvalidArgumentException
*/
public function __construct(UrlGeneratorInterface $urlGenerator = null, $urlMatcher = null, $domainRegexp = null)
{
$this->urlGenerator = $urlGenerator;
if ($urlMatcher !== null && !$urlMatcher instanceof UrlMatcherInterface && !$urlMatcher instanceof RequestMatcherInterface) {
throw new \InvalidArgumentException('Matcher must either implement UrlMatcherInterface or RequestMatcherInterface.');
}
$this->urlMatcher = $urlMatcher;
$this->domainRegexp = $domainRegexp;
}
/**
* Creates a redirect Response.
*
* @param Request $request A Request instance
* @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
* @param int $status The status code
*
* @return RedirectResponse A RedirectResponse instance
*/
public function createRedirectResponse(Request $request, $path, $status = 302)
{
if (null !== $this->domainRegexp && preg_match('#^https?://[^/]++#i', $path, $host) && !preg_match(sprintf($this->domainRegexp, preg_quote($request->getHttpHost())), $host[0])) {
$path = '/';
}
return new RedirectResponse($this->generateUri($request, $path), $status);
}
/**
* Creates a Request.
*
* @param Request $request The current Request instance
* @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
*
* @return Request A Request instance
*/
public function createRequest(Request $request, $path)
{
$newRequest = Request::create($this->generateUri($request, $path), 'get', array(), $request->cookies->all(), array(), $request->server->all());
if ($request->hasSession()) {
$newRequest->setSession($request->getSession());
}
if ($request->attributes->has(Security::AUTHENTICATION_ERROR)) {
$newRequest->attributes->set(Security::AUTHENTICATION_ERROR, $request->attributes->get(Security::AUTHENTICATION_ERROR));
}
if ($request->attributes->has(Security::ACCESS_DENIED_ERROR)) {
$newRequest->attributes->set(Security::ACCESS_DENIED_ERROR, $request->attributes->get(Security::ACCESS_DENIED_ERROR));
}
if ($request->attributes->has(Security::LAST_USERNAME)) {
$newRequest->attributes->set(Security::LAST_USERNAME, $request->attributes->get(Security::LAST_USERNAME));
}
return $newRequest;
}
/**
* Checks that a given path matches the Request.
*
* @param Request $request A Request instance
* @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
*
* @return bool true if the path is the same as the one from the Request, false otherwise
*/
public function checkRequestPath(Request $request, $path)
{
if ('/' !== $path[0]) {
try {
// matching a request is more powerful than matching a URL path + context, so try that first
if ($this->urlMatcher instanceof RequestMatcherInterface) {
$parameters = $this->urlMatcher->matchRequest($request);
} else {
$parameters = $this->urlMatcher->match($request->getPathInfo());
}
return isset($parameters['_route']) && $path === $parameters['_route'];
} catch (MethodNotAllowedException $e) {
return false;
} catch (ResourceNotFoundException $e) {
return false;
}
}
return $path === rawurldecode($request->getPathInfo());
}
/**
* Generates a URI, based on the given path or absolute URL.
*
* @param Request $request A Request instance
* @param string $path A path (an absolute path (/foo), an absolute URL (http://...), or a route name (foo))
*
* @return string An absolute URL
*
* @throws \LogicException
*/
public function generateUri($request, $path)
{
if (0 === strpos($path, 'http') || !$path) {
return $path;
}
if ('/' === $path[0]) {
return $request->getUriForPath($path);
}
if (null === $this->urlGenerator) {
throw new \LogicException('You must provide a UrlGeneratorInterface instance to be able to use routes.');
}
$url = $this->urlGenerator->generate($path, $request->attributes->all(), UrlGeneratorInterface::ABSOLUTE_URL);
// unnecessary query string parameters must be removed from URL
// (ie. query parameters that are presents in $attributes)
// fortunately, they all are, so we have to remove entire query string
$position = strpos($url, '?');
if (false !== $position) {
$url = substr($url, 0, $position);
}
return $url;
}
}

19
vendor/symfony/security/Http/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2004-2017 Fabien Potencier
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,50 @@
<?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\Logout;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* This handler clears the passed cookies when a user logs out.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class CookieClearingLogoutHandler implements LogoutHandlerInterface
{
private $cookies;
/**
* Constructor.
*
* @param array $cookies An array of cookie names to unset
*/
public function __construct(array $cookies)
{
$this->cookies = $cookies;
}
/**
* Implementation for the LogoutHandlerInterface. Deletes all requested cookies.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token
*/
public function logout(Request $request, Response $response, TokenInterface $token)
{
foreach ($this->cookies as $cookieName => $cookieData) {
$response->headers->clearCookie($cookieName, $cookieData['path'], $cookieData['domain']);
}
}
}

View File

@@ -0,0 +1,46 @@
<?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\Logout;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\HttpUtils;
/**
* Default logout success handler will redirect users to a configured path.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Alexander <iam.asm89@gmail.com>
*/
class DefaultLogoutSuccessHandler implements LogoutSuccessHandlerInterface
{
protected $httpUtils;
protected $targetUrl;
/**
* @param HttpUtils $httpUtils
* @param string $targetUrl
*/
public function __construct(HttpUtils $httpUtils, $targetUrl = '/')
{
$this->httpUtils = $httpUtils;
$this->targetUrl = $targetUrl;
}
/**
* {@inheritdoc}
*/
public function onLogoutSuccess(Request $request)
{
return $this->httpUtils->createRedirectResponse($request, $this->targetUrl);
}
}

View File

@@ -0,0 +1,35 @@
<?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\Logout;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* Interface that needs to be implemented by LogoutHandlers.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface LogoutHandlerInterface
{
/**
* This method is called by the LogoutListener when a user has requested
* to be logged out. Usually, you would unset session variables, or remove
* cookies, etc.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token
*/
public function logout(Request $request, Response $response, TokenInterface $token);
}

View File

@@ -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\Component\Security\Http\Logout;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
/**
* LogoutSuccesshandlerInterface.
*
* In contrast to the LogoutHandlerInterface, this interface can return a response
* which is then used instead of the default behavior.
*
* If you want to only perform some logout related clean-up task, use the
* LogoutHandlerInterface instead.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface LogoutSuccessHandlerInterface
{
/**
* Creates a Response object to send upon a successful logout.
*
* @param Request $request
*
* @return Response never null
*/
public function onLogoutSuccess(Request $request);
}

View File

@@ -0,0 +1,135 @@
<?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\Logout;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
/**
* Provides generator functions for the logout URL.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jeremy Mikola <jmikola@gmail.com>
*/
class LogoutUrlGenerator
{
private $requestStack;
private $router;
private $tokenStorage;
private $listeners = array();
public function __construct(RequestStack $requestStack = null, UrlGeneratorInterface $router = null, TokenStorageInterface $tokenStorage = null)
{
$this->requestStack = $requestStack;
$this->router = $router;
$this->tokenStorage = $tokenStorage;
}
/**
* Registers a firewall's LogoutListener, allowing its URL to be generated.
*
* @param string $key The firewall key
* @param string $logoutPath The path that starts the logout process
* @param string $csrfTokenId The ID of the CSRF token
* @param string $csrfParameter The CSRF token parameter name
* @param CsrfTokenManagerInterface $csrfTokenManager A CsrfTokenManagerInterface instance
*/
public function registerListener($key, $logoutPath, $csrfTokenId, $csrfParameter, CsrfTokenManagerInterface $csrfTokenManager = null)
{
$this->listeners[$key] = array($logoutPath, $csrfTokenId, $csrfParameter, $csrfTokenManager);
}
/**
* Generates the absolute logout path for the firewall.
*
* @param string|null $key The firewall key or null to use the current firewall key
*
* @return string The logout path
*/
public function getLogoutPath($key = null)
{
return $this->generateLogoutUrl($key, UrlGeneratorInterface::ABSOLUTE_PATH);
}
/**
* Generates the absolute logout URL for the firewall.
*
* @param string|null $key The firewall key or null to use the current firewall key
*
* @return string The logout URL
*/
public function getLogoutUrl($key = null)
{
return $this->generateLogoutUrl($key, UrlGeneratorInterface::ABSOLUTE_URL);
}
/**
* Generates the logout URL for the firewall.
*
* @param string|null $key The firewall key or null to use the current firewall key
* @param int $referenceType The type of reference (one of the constants in UrlGeneratorInterface)
*
* @return string The logout URL
*
* @throws \InvalidArgumentException if no LogoutListener is registered for the key or the key could not be found automatically.
*/
private function generateLogoutUrl($key, $referenceType)
{
// Fetch the current provider key from token, if possible
if (null === $key && null !== $this->tokenStorage) {
$token = $this->tokenStorage->getToken();
if (null !== $token && method_exists($token, 'getProviderKey')) {
$key = $token->getProviderKey();
}
}
if (null === $key) {
throw new \InvalidArgumentException('Unable to find the current firewall LogoutListener, please provide the provider key manually.');
}
if (!array_key_exists($key, $this->listeners)) {
throw new \InvalidArgumentException(sprintf('No LogoutListener found for firewall key "%s".', $key));
}
list($logoutPath, $csrfTokenId, $csrfParameter, $csrfTokenManager) = $this->listeners[$key];
if (null === $logoutPath) {
throw new \LogicException('Unable to generate the logout URL without a path.');
}
$parameters = null !== $csrfTokenManager ? array($csrfParameter => (string) $csrfTokenManager->getToken($csrfTokenId)) : array();
if ('/' === $logoutPath[0]) {
if (!$this->requestStack) {
throw new \LogicException('Unable to generate the logout URL without a RequestStack.');
}
$request = $this->requestStack->getCurrentRequest();
$url = UrlGeneratorInterface::ABSOLUTE_URL === $referenceType ? $request->getUriForPath($logoutPath) : $request->getBaseUrl().$logoutPath;
if (!empty($parameters)) {
$url .= '?'.http_build_query($parameters);
}
} else {
if (!$this->router) {
throw new \LogicException('Unable to generate the logout URL without a Router.');
}
$url = $this->router->generate($logoutPath, $parameters, $referenceType);
}
return $url;
}
}

View File

@@ -0,0 +1,36 @@
<?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\Logout;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* Handler for clearing invalidating the current session.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class SessionLogoutHandler implements LogoutHandlerInterface
{
/**
* Invalidate the current session.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token
*/
public function logout(Request $request, Response $response, TokenInterface $token)
{
$request->getSession()->invalidate();
}
}

View File

@@ -0,0 +1,96 @@
<?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;
use Symfony\Component\HttpFoundation\ParameterBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PropertyAccess\Exception\AccessException;
use Symfony\Component\PropertyAccess\Exception\InvalidArgumentException;
use Symfony\Component\PropertyAccess\PropertyAccess;
/**
* @internal
*/
final class ParameterBagUtils
{
private static $propertyAccessor;
/**
* Returns a "parameter" value.
*
* Paths like foo[bar] will be evaluated to find deeper items in nested data structures.
*
* @param ParameterBag $parameters The parameter bag
* @param string $path The key
*
* @return mixed
*
* @throws InvalidArgumentException when the given path is malformed
*/
public static function getParameterBagValue(ParameterBag $parameters, $path)
{
if (false === $pos = strpos($path, '[')) {
return $parameters->get($path);
}
$root = substr($path, 0, $pos);
if (null === $value = $parameters->get($root)) {
return;
}
if (null === self::$propertyAccessor) {
self::$propertyAccessor = PropertyAccess::createPropertyAccessor();
}
try {
return self::$propertyAccessor->getValue($value, substr($path, $pos));
} catch (AccessException $e) {
return;
}
}
/**
* Returns a request "parameter" value.
*
* Paths like foo[bar] will be evaluated to find deeper items in nested data structures.
*
* @param Request $request The request
* @param string $path The key
*
* @return mixed
*
* @throws InvalidArgumentException when the given path is malformed
*/
public static function getRequestParameterValue(Request $request, $path)
{
if (false === $pos = strpos($path, '[')) {
return $request->get($path);
}
$root = substr($path, 0, $pos);
if (null === $value = $request->get($root)) {
return;
}
if (null === self::$propertyAccessor) {
self::$propertyAccessor = PropertyAccess::createPropertyAccessor();
}
try {
return self::$propertyAccessor->getValue($value, substr($path, $pos));
} catch (AccessException $e) {
return;
}
}
}

16
vendor/symfony/security/Http/README.md vendored Normal file
View File

@@ -0,0 +1,16 @@
Security Component - HTTP Integration
=====================================
Security provides an infrastructure for sophisticated authorization systems,
which makes it possible to easily separate the actual authorization logic from
so called user providers that hold the users credentials. It is inspired by
the Java Spring framework.
Resources
---------
* [Documentation](https://symfony.com/doc/current/components/security/index.html)
* [Contributing](https://symfony.com/doc/current/contributing/index.html)
* [Report issues](https://github.com/symfony/symfony/issues) and
[send Pull Requests](https://github.com/symfony/symfony/pulls)
in the [main Symfony repository](https://github.com/symfony/symfony)

View File

@@ -0,0 +1,324 @@
<?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\RememberMe;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Exception\CookieTheftException;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Cookie;
use Psr\Log\LoggerInterface;
use Symfony\Component\Security\Http\ParameterBagUtils;
/**
* Base class implementing the RememberMeServicesInterface.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
abstract class AbstractRememberMeServices implements RememberMeServicesInterface, LogoutHandlerInterface
{
const COOKIE_DELIMITER = ':';
protected $logger;
protected $options = array(
'secure' => false,
'httponly' => true,
);
private $providerKey;
private $secret;
private $userProviders;
/**
* Constructor.
*
* @param array $userProviders
* @param string $secret
* @param string $providerKey
* @param array $options
* @param LoggerInterface $logger
*
* @throws \InvalidArgumentException
*/
public function __construct(array $userProviders, $secret, $providerKey, array $options = array(), LoggerInterface $logger = null)
{
if (empty($secret)) {
throw new \InvalidArgumentException('$secret must not be empty.');
}
if (empty($providerKey)) {
throw new \InvalidArgumentException('$providerKey must not be empty.');
}
if (0 === count($userProviders)) {
throw new \InvalidArgumentException('You must provide at least one user provider.');
}
$this->userProviders = $userProviders;
$this->secret = $secret;
$this->providerKey = $providerKey;
$this->options = array_merge($this->options, $options);
$this->logger = $logger;
}
/**
* Returns the parameter that is used for checking whether remember-me
* services have been requested.
*
* @return string
*/
public function getRememberMeParameter()
{
return $this->options['remember_me_parameter'];
}
/**
* @return string
*/
public function getSecret()
{
return $this->secret;
}
/**
* Implementation of RememberMeServicesInterface. Detects whether a remember-me
* cookie was set, decodes it, and hands it to subclasses for further processing.
*
* @param Request $request
*
* @return TokenInterface|null
*
* @throws CookieTheftException
* @throws \RuntimeException
*/
final public function autoLogin(Request $request)
{
if (null === $cookie = $request->cookies->get($this->options['name'])) {
return;
}
if (null !== $this->logger) {
$this->logger->debug('Remember-me cookie detected.');
}
$cookieParts = $this->decodeCookie($cookie);
try {
$user = $this->processAutoLoginCookie($cookieParts, $request);
if (!$user instanceof UserInterface) {
throw new \RuntimeException('processAutoLoginCookie() must return a UserInterface implementation.');
}
if (null !== $this->logger) {
$this->logger->info('Remember-me cookie accepted.');
}
return new RememberMeToken($user, $this->providerKey, $this->secret);
} catch (CookieTheftException $e) {
$this->cancelCookie($request);
throw $e;
} catch (UsernameNotFoundException $e) {
if (null !== $this->logger) {
$this->logger->info('User for remember-me cookie not found.');
}
} catch (UnsupportedUserException $e) {
if (null !== $this->logger) {
$this->logger->warning('User class for remember-me cookie not supported.');
}
} catch (AuthenticationException $e) {
if (null !== $this->logger) {
$this->logger->debug('Remember-Me authentication failed.', array('exception' => $e));
}
}
$this->cancelCookie($request);
}
/**
* Implementation for LogoutHandlerInterface. Deletes the cookie.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token
*/
public function logout(Request $request, Response $response, TokenInterface $token)
{
$this->cancelCookie($request);
}
/**
* Implementation for RememberMeServicesInterface. Deletes the cookie when
* an attempted authentication fails.
*
* @param Request $request
*/
final public function loginFail(Request $request)
{
$this->cancelCookie($request);
$this->onLoginFail($request);
}
/**
* Implementation for RememberMeServicesInterface. This is called when an
* authentication is successful.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token The token that resulted in a successful authentication
*/
final public function loginSuccess(Request $request, Response $response, TokenInterface $token)
{
// Make sure any old remember-me cookies are cancelled
$this->cancelCookie($request);
if (!$token->getUser() instanceof UserInterface) {
if (null !== $this->logger) {
$this->logger->debug('Remember-me ignores token since it does not contain a UserInterface implementation.');
}
return;
}
if (!$this->isRememberMeRequested($request)) {
if (null !== $this->logger) {
$this->logger->debug('Remember-me was not requested.');
}
return;
}
if (null !== $this->logger) {
$this->logger->debug('Remember-me was requested; setting cookie.');
}
// Remove attribute from request that sets a NULL cookie.
// It was set by $this->cancelCookie()
// (cancelCookie does other things too for some RememberMeServices
// so we should still call it at the start of this method)
$request->attributes->remove(self::COOKIE_ATTR_NAME);
$this->onLoginSuccess($request, $response, $token);
}
/**
* Subclasses should validate the cookie and do any additional processing
* that is required. This is called from autoLogin().
*
* @param array $cookieParts
* @param Request $request
*
* @return UserInterface
*/
abstract protected function processAutoLoginCookie(array $cookieParts, Request $request);
/**
* @param Request $request
*/
protected function onLoginFail(Request $request)
{
}
/**
* This is called after a user has been logged in successfully, and has
* requested remember-me capabilities. The implementation usually sets a
* cookie and possibly stores a persistent record of it.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token
*/
abstract protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token);
final protected function getUserProvider($class)
{
foreach ($this->userProviders as $provider) {
if ($provider->supportsClass($class)) {
return $provider;
}
}
throw new UnsupportedUserException(sprintf('There is no user provider that supports class "%s".', $class));
}
/**
* Decodes the raw cookie value.
*
* @param string $rawCookie
*
* @return array
*/
protected function decodeCookie($rawCookie)
{
return explode(self::COOKIE_DELIMITER, base64_decode($rawCookie));
}
/**
* Encodes the cookie parts.
*
* @param array $cookieParts
*
* @return string
*
* @throws \InvalidArgumentException When $cookieParts contain the cookie delimiter. Extending class should either remove or escape it.
*/
protected function encodeCookie(array $cookieParts)
{
foreach ($cookieParts as $cookiePart) {
if (false !== strpos($cookiePart, self::COOKIE_DELIMITER)) {
throw new \InvalidArgumentException(sprintf('$cookieParts should not contain the cookie delimiter "%s"', self::COOKIE_DELIMITER));
}
}
return base64_encode(implode(self::COOKIE_DELIMITER, $cookieParts));
}
/**
* Deletes the remember-me cookie.
*
* @param Request $request
*/
protected function cancelCookie(Request $request)
{
if (null !== $this->logger) {
$this->logger->debug('Clearing remember-me cookie.', array('name' => $this->options['name']));
}
$request->attributes->set(self::COOKIE_ATTR_NAME, new Cookie($this->options['name'], null, 1, $this->options['path'], $this->options['domain'], $this->options['secure'], $this->options['httponly']));
}
/**
* Checks whether remember-me capabilities were requested.
*
* @param Request $request
*
* @return bool
*/
protected function isRememberMeRequested(Request $request)
{
if (true === $this->options['always_remember_me']) {
return true;
}
$parameter = ParameterBagUtils::getRequestParameterValue($request, $this->options['remember_me_parameter']);
if (null === $parameter && null !== $this->logger) {
$this->logger->debug('Did not send remember-me cookie.', array('parameter' => $this->options['remember_me_parameter']));
}
return $parameter === 'true' || $parameter === 'on' || $parameter === '1' || $parameter === 'yes' || $parameter === true;
}
}

View File

@@ -0,0 +1,128 @@
<?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\RememberMe;
use Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\CookieTheftException;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
/**
* Concrete implementation of the RememberMeServicesInterface which needs
* an implementation of TokenProviderInterface for providing remember-me
* capabilities.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class PersistentTokenBasedRememberMeServices extends AbstractRememberMeServices
{
private $tokenProvider;
/**
* Sets the token provider.
*
* @param TokenProviderInterface $tokenProvider
*/
public function setTokenProvider(TokenProviderInterface $tokenProvider)
{
$this->tokenProvider = $tokenProvider;
}
/**
* {@inheritdoc}
*/
protected function cancelCookie(Request $request)
{
// Delete cookie on the client
parent::cancelCookie($request);
// Delete cookie from the tokenProvider
if (null !== ($cookie = $request->cookies->get($this->options['name']))
&& count($parts = $this->decodeCookie($cookie)) === 2
) {
list($series) = $parts;
$this->tokenProvider->deleteTokenBySeries($series);
}
}
/**
* {@inheritdoc}
*/
protected function processAutoLoginCookie(array $cookieParts, Request $request)
{
if (count($cookieParts) !== 2) {
throw new AuthenticationException('The cookie is invalid.');
}
list($series, $tokenValue) = $cookieParts;
$persistentToken = $this->tokenProvider->loadTokenBySeries($series);
if (!hash_equals($persistentToken->getTokenValue(), $tokenValue)) {
throw new CookieTheftException('This token was already used. The account is possibly compromised.');
}
if ($persistentToken->getLastUsed()->getTimestamp() + $this->options['lifetime'] < time()) {
throw new AuthenticationException('The cookie has expired.');
}
$tokenValue = base64_encode(random_bytes(64));
$this->tokenProvider->updateToken($series, $tokenValue, new \DateTime());
$request->attributes->set(self::COOKIE_ATTR_NAME,
new Cookie(
$this->options['name'],
$this->encodeCookie(array($series, $tokenValue)),
time() + $this->options['lifetime'],
$this->options['path'],
$this->options['domain'],
$this->options['secure'],
$this->options['httponly']
)
);
return $this->getUserProvider($persistentToken->getClass())->loadUserByUsername($persistentToken->getUsername());
}
/**
* {@inheritdoc}
*/
protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token)
{
$series = base64_encode(random_bytes(64));
$tokenValue = base64_encode(random_bytes(64));
$this->tokenProvider->createNewToken(
new PersistentToken(
get_class($user = $token->getUser()),
$user->getUsername(),
$series,
$tokenValue,
new \DateTime()
)
);
$response->headers->setCookie(
new Cookie(
$this->options['name'],
$this->encodeCookie(array($series, $tokenValue)),
time() + $this->options['lifetime'],
$this->options['path'],
$this->options['domain'],
$this->options['secure'],
$this->options['httponly']
)
);
}
}

View File

@@ -0,0 +1,83 @@
<?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\RememberMe;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
/**
* Interface that needs to be implemented by classes which provide remember-me
* capabilities.
*
* We provide two implementations out-of-the-box:
* - TokenBasedRememberMeServices (does not require a TokenProvider)
* - PersistentTokenBasedRememberMeServices (requires a TokenProvider)
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface RememberMeServicesInterface
{
/**
* This attribute name can be used by the implementation if it needs to set
* a cookie on the Request when there is no actual Response, yet.
*
* @var string
*/
const COOKIE_ATTR_NAME = '_security_remember_me_cookie';
/**
* This method will be called whenever the TokenStorage does not contain
* a TokenInterface object and the framework wishes to provide an implementation
* with an opportunity to authenticate the request using remember-me capabilities.
*
* No attempt whatsoever is made to determine whether the browser has requested
* remember-me services or presented a valid cookie. Any and all such determinations
* are left to the implementation of this method.
*
* If a browser has presented an unauthorised cookie for whatever reason,
* make sure to throw an AuthenticationException as this will consequentially
* result in a call to loginFail() and therefore an invalidation of the cookie.
*
* @param Request $request
*
* @return TokenInterface
*/
public function autoLogin(Request $request);
/**
* Called whenever an interactive authentication attempt was made, but the
* credentials supplied by the user were missing or otherwise invalid.
*
* This method needs to take care of invalidating the cookie.
*
* @param Request $request
*/
public function loginFail(Request $request);
/**
* Called whenever an interactive authentication attempt is successful
* (e.g. a form login).
*
* An implementation may always set a remember-me cookie in the Response,
* although this is not recommended.
*
* Instead, implementations should typically look for a request parameter
* (such as a HTTP POST parameter) that indicates the browser has explicitly
* requested for the authentication to be remembered.
*
* @param Request $request
* @param Response $response
* @param TokenInterface $token
*/
public function loginSuccess(Request $request, Response $response, TokenInterface $token);
}

View File

@@ -0,0 +1,49 @@
<?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\RememberMe;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Adds remember-me cookies to the Response.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class ResponseListener implements EventSubscriberInterface
{
/**
* @param FilterResponseEvent $event
*/
public function onKernelResponse(FilterResponseEvent $event)
{
if (!$event->isMasterRequest()) {
return;
}
$request = $event->getRequest();
$response = $event->getResponse();
if ($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME)) {
$response->headers->setCookie($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME));
}
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents()
{
return array(KernelEvents::RESPONSE => 'onKernelResponse');
}
}

View File

@@ -0,0 +1,125 @@
<?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\RememberMe;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\User\UserInterface;
/**
* Concrete implementation of the RememberMeServicesInterface providing
* remember-me capabilities without requiring a TokenProvider.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class TokenBasedRememberMeServices extends AbstractRememberMeServices
{
/**
* {@inheritdoc}
*/
protected function processAutoLoginCookie(array $cookieParts, Request $request)
{
if (count($cookieParts) !== 4) {
throw new AuthenticationException('The cookie is invalid.');
}
list($class, $username, $expires, $hash) = $cookieParts;
if (false === $username = base64_decode($username, true)) {
throw new AuthenticationException('$username contains a character from outside the base64 alphabet.');
}
try {
$user = $this->getUserProvider($class)->loadUserByUsername($username);
} catch (\Exception $e) {
if (!$e instanceof AuthenticationException) {
$e = new AuthenticationException($e->getMessage(), $e->getCode(), $e);
}
throw $e;
}
if (!$user instanceof UserInterface) {
throw new \RuntimeException(sprintf('The UserProviderInterface implementation must return an instance of UserInterface, but returned "%s".', get_class($user)));
}
if (true !== hash_equals($this->generateCookieHash($class, $username, $expires, $user->getPassword()), $hash)) {
throw new AuthenticationException('The cookie\'s hash is invalid.');
}
if ($expires < time()) {
throw new AuthenticationException('The cookie has expired.');
}
return $user;
}
/**
* {@inheritdoc}
*/
protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token)
{
$user = $token->getUser();
$expires = time() + $this->options['lifetime'];
$value = $this->generateCookieValue(get_class($user), $user->getUsername(), $expires, $user->getPassword());
$response->headers->setCookie(
new Cookie(
$this->options['name'],
$value,
$expires,
$this->options['path'],
$this->options['domain'],
$this->options['secure'],
$this->options['httponly']
)
);
}
/**
* Generates the cookie value.
*
* @param string $class
* @param string $username The username
* @param int $expires The Unix timestamp when the cookie expires
* @param string $password The encoded password
*
* @return string
*/
protected function generateCookieValue($class, $username, $expires, $password)
{
// $username is encoded because it might contain COOKIE_DELIMITER,
// we assume other values don't
return $this->encodeCookie(array(
$class,
base64_encode($username),
$expires,
$this->generateCookieHash($class, $username, $expires, $password),
));
}
/**
* Generates a hash for the cookie to ensure it is not being tempered with.
*
* @param string $class
* @param string $username The username
* @param int $expires The Unix timestamp when the cookie expires
* @param string $password The encoded password
*
* @return string
*/
protected function generateCookieHash($class, $username, $expires, $password)
{
return hash_hmac('sha256', $class.$username.$expires.$password, $this->getSecret());
}
}

View File

@@ -0,0 +1,35 @@
<?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;
final class SecurityEvents
{
/**
* The INTERACTIVE_LOGIN event occurs after a user is logged in
* interactively for authentication based on http, cookies or X509.
*
* @Event("Symfony\Component\Security\Http\Event\InteractiveLoginEvent")
*
* @var string
*/
const INTERACTIVE_LOGIN = 'security.interactive_login';
/**
* The SWITCH_USER event occurs before switch to another user and
* before exit from an already switched user.
*
* @Event("Symfony\Component\Security\Http\Event\SwitchUserEvent")
*
* @var string
*/
const SWITCH_USER = 'security.switch_user';
}

View File

@@ -0,0 +1,63 @@
<?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\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* The default session strategy implementation.
*
* Supports the following strategies:
* NONE: the session is not changed
* MIGRATE: the session id is updated, attributes are kept
* INVALIDATE: the session id is updated, attributes are lost
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
class SessionAuthenticationStrategy implements SessionAuthenticationStrategyInterface
{
const NONE = 'none';
const MIGRATE = 'migrate';
const INVALIDATE = 'invalidate';
private $strategy;
public function __construct($strategy)
{
$this->strategy = $strategy;
}
/**
* {@inheritdoc}
*/
public function onAuthentication(Request $request, TokenInterface $token)
{
switch ($this->strategy) {
case self::NONE:
return;
case self::MIGRATE:
$request->getSession()->migrate(true);
return;
case self::INVALIDATE:
$request->getSession()->invalidate();
return;
default:
throw new \RuntimeException(sprintf('Invalid session authentication strategy "%s"', $this->strategy));
}
}
}

View File

@@ -0,0 +1,37 @@
<?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\Session;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* SessionAuthenticationStrategyInterface.
*
* Implementation are responsible for updating the session after an interactive
* authentication attempt was successful.
*
* @author Johannes M. Schmitt <schmittjoh@gmail.com>
*/
interface SessionAuthenticationStrategyInterface
{
/**
* This performs any necessary changes to the session.
*
* This method is called before the TokenStorage is populated with a
* Token, and only by classes inheriting from AbstractAuthenticationListener.
*
* @param Request $request
* @param TokenInterface $token
*/
public function onAuthentication(Request $request, TokenInterface $token);
}

View File

@@ -0,0 +1,52 @@
<?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\Security\Http\AccessMap;
class AccessMapTest extends TestCase
{
public function testReturnsFirstMatchedPattern()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$requestMatcher1 = $this->getRequestMatcher($request, false);
$requestMatcher2 = $this->getRequestMatcher($request, true);
$map = new AccessMap();
$map->add($requestMatcher1, array('ROLE_ADMIN'), 'http');
$map->add($requestMatcher2, array('ROLE_USER'), 'https');
$this->assertSame(array(array('ROLE_USER'), 'https'), $map->getPatterns($request));
}
public function testReturnsEmptyPatternIfNoneMatched()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$requestMatcher = $this->getRequestMatcher($request, false);
$map = new AccessMap();
$map->add($requestMatcher, array('ROLE_USER'), 'https');
$this->assertSame(array(null, null), $map->getPatterns($request));
}
private function getRequestMatcher($request, $matches)
{
$requestMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcherInterface')->getMock();
$requestMatcher->expects($this->once())
->method('matches')->with($request)
->will($this->returnValue($matches));
return $requestMatcher;
}
}

View File

@@ -0,0 +1,190 @@
<?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\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationFailureHandler;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class DefaultAuthenticationFailureHandlerTest extends TestCase
{
private $httpKernel;
private $httpUtils;
private $logger;
private $request;
private $session;
private $exception;
protected function setUp()
{
$this->httpKernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$this->httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$this->logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$this->session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$this->request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$this->request->expects($this->any())->method('getSession')->will($this->returnValue($this->session));
$this->exception = $this->getMockBuilder('Symfony\Component\Security\Core\Exception\AuthenticationException')->setMethods(array('getMessage'))->getMock();
}
public function testForward()
{
$options = array('failure_forward' => true);
$subRequest = $this->getRequest();
$subRequest->attributes->expects($this->once())
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
$this->httpUtils->expects($this->once())
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($subRequest));
$response = new Response();
$this->httpKernel->expects($this->once())
->method('handle')->with($subRequest, HttpKernelInterface::SUB_REQUEST)
->will($this->returnValue($response));
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$result = $handler->onAuthenticationFailure($this->request, $this->exception);
$this->assertSame($response, $result);
}
public function testRedirect()
{
$response = new Response();
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/login')
->will($this->returnValue($response));
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$result = $handler->onAuthenticationFailure($this->request, $this->exception);
$this->assertSame($response, $result);
}
public function testExceptionIsPersistedInSession()
{
$this->session->expects($this->once())
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testExceptionIsPassedInRequestOnForward()
{
$options = array('failure_forward' => true);
$subRequest = $this->getRequest();
$subRequest->attributes->expects($this->once())
->method('set')->with(Security::AUTHENTICATION_ERROR, $this->exception);
$this->httpUtils->expects($this->once())
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($subRequest));
$this->session->expects($this->never())->method('set');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testRedirectIsLogged()
{
$this->logger
->expects($this->once())
->method('debug')
->with('Authentication failure, redirect triggered.', array('failure_path' => '/login'));
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testForwardIsLogged()
{
$options = array('failure_forward' => true);
$this->httpUtils->expects($this->once())
->method('createRequest')->with($this->request, '/login')
->will($this->returnValue($this->getRequest()));
$this->logger
->expects($this->once())
->method('debug')
->with('Authentication failure, forward triggered.', array('failure_path' => '/login'));
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testFailurePathCanBeOverwritten()
{
$options = array('failure_path' => '/auth/login');
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testFailurePathCanBeOverwrittenWithRequest()
{
$this->request->expects($this->once())
->method('get')->with('_failure_path')
->will($this->returnValue('/auth/login'));
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array(), $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testFailurePathCanBeOverwrittenWithNestedAttributeInRequest()
{
$this->request->expects($this->once())
->method('get')->with('_failure_path')
->will($this->returnValue(array('value' => '/auth/login')));
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, array('failure_path_parameter' => '_failure_path[value]'), $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
public function testFailurePathParameterCanBeOverwritten()
{
$options = array('failure_path_parameter' => '_my_failure_path');
$this->request->expects($this->once())
->method('get')->with('_my_failure_path')
->will($this->returnValue('/auth/login'));
$this->httpUtils->expects($this->once())
->method('createRedirectResponse')->with($this->request, '/auth/login');
$handler = new DefaultAuthenticationFailureHandler($this->httpKernel, $this->httpUtils, $options, $this->logger);
$handler->onAuthenticationFailure($this->request, $this->exception);
}
private function getRequest()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request->attributes = $this->getMockBuilder('Symfony\Component\HttpFoundation\ParameterBag')->getMock();
return $request;
}
}

View File

@@ -0,0 +1,103 @@
<?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\Authentication;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Authentication\DefaultAuthenticationSuccessHandler;
use Symfony\Component\Security\Http\HttpUtils;
class DefaultAuthenticationSuccessHandlerTest extends TestCase
{
/**
* @dataProvider getRequestRedirections
*/
public function testRequestRedirections(Request $request, $options, $redirectedUrl)
{
$urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock();
$urlGenerator->expects($this->any())->method('generate')->will($this->returnValue('http://localhost/login'));
$httpUtils = new HttpUtils($urlGenerator);
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$handler = new DefaultAuthenticationSuccessHandler($httpUtils, $options);
if ($request->hasSession()) {
$handler->setProviderKey('admin');
}
$this->assertSame('http://localhost'.$redirectedUrl, $handler->onAuthenticationSuccess($request, $token)->getTargetUrl());
}
public function getRequestRedirections()
{
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session->expects($this->once())->method('get')->with('_security.admin.target_path')->will($this->returnValue('/admin/dashboard'));
$session->expects($this->once())->method('remove')->with('_security.admin.target_path');
$requestWithSession = Request::create('/');
$requestWithSession->setSession($session);
return array(
'default' => array(
Request::create('/'),
array(),
'/',
),
'forced target path' => array(
Request::create('/'),
array('always_use_default_target_path' => true, 'default_target_path' => '/dashboard'),
'/dashboard',
),
'target path as query string' => array(
Request::create('/?_target_path=/dashboard'),
array(),
'/dashboard',
),
'target path name as query string is customized' => array(
Request::create('/?_my_target_path=/dashboard'),
array('target_path_parameter' => '_my_target_path'),
'/dashboard',
),
'target path name as query string is customized and nested' => array(
Request::create('/?_target_path[value]=/dashboard'),
array('target_path_parameter' => '_target_path[value]'),
'/dashboard',
),
'target path in session' => array(
$requestWithSession,
array(),
'/admin/dashboard',
),
'target path as referer' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/dashboard')),
array('use_referer' => true),
'/dashboard',
),
'target path as referer is ignored if not configured' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/dashboard')),
array(),
'/',
),
'target path should be different than login URL' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/login')),
array('use_referer' => true, 'login_path' => '/login'),
'/',
),
'target path should be different than login URL (query string does not matter)' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/login?t=1&p=2')),
array('use_referer' => true, 'login_path' => '/login'),
'/',
),
'target path should be different than login URL (login_path as a route)' => array(
Request::create('/', 'GET', array(), array(), array(), array('HTTP_REFERER' => 'http://localhost/login?t=1&p=2')),
array('use_referer' => true, 'login_path' => 'login_route'),
'/',
),
);
}
}

View File

@@ -0,0 +1,196 @@
<?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;
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)
->will($this->returnValue($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)
->will($this->returnValue($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)
->will($this->returnValue(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)
->will($this->returnValue($this->response));
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestSuccessHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationSuccess')
->with($this->request, $this->token)
->will($this->returnValue(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)
->will($this->returnValue($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)
->will($this->returnValue($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)
->will($this->returnValue(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)
->will($this->returnValue($this->response));
$authenticator = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Tests\TestFailureHandlerInterface');
$authenticator->expects($this->once())
->method('onAuthenticationFailure')
->with($this->request, $this->authenticationException)
->will($this->returnValue(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

@@ -0,0 +1,44 @@
<?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\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\EntryPoint\BasicAuthenticationEntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
class BasicAuthenticationEntryPointTest extends TestCase
{
public function testStart()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$authException = new AuthenticationException('The exception message');
$entryPoint = new BasicAuthenticationEntryPoint('TheRealmName');
$response = $entryPoint->start($request, $authException);
$this->assertEquals('Basic realm="TheRealmName"', $response->headers->get('WWW-Authenticate'));
$this->assertEquals(401, $response->getStatusCode());
}
public function testStartWithoutAuthException()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$entryPoint = new BasicAuthenticationEntryPoint('TheRealmName');
$response = $entryPoint->start($request);
$this->assertEquals('Basic realm="TheRealmName"', $response->headers->get('WWW-Authenticate'));
$this->assertEquals(401, $response->getStatusCode());
}
}

View File

@@ -0,0 +1,57 @@
<?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\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Core\Exception\NonceExpiredException;
class DigestAuthenticationEntryPointTest extends TestCase
{
public function testStart()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$authenticationException = new AuthenticationException('TheAuthenticationExceptionMessage');
$entryPoint = new DigestAuthenticationEntryPoint('TheRealmName', 'TheSecret');
$response = $entryPoint->start($request, $authenticationException);
$this->assertEquals(401, $response->getStatusCode());
$this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
}
public function testStartWithNoException()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$entryPoint = new DigestAuthenticationEntryPoint('TheRealmName', 'TheSecret');
$response = $entryPoint->start($request);
$this->assertEquals(401, $response->getStatusCode());
$this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}"$/', $response->headers->get('WWW-Authenticate'));
}
public function testStartWithNonceExpiredException()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$nonceExpiredException = new NonceExpiredException('TheNonceExpiredExceptionMessage');
$entryPoint = new DigestAuthenticationEntryPoint('TheRealmName', 'TheSecret');
$response = $entryPoint->start($request, $nonceExpiredException);
$this->assertEquals(401, $response->getStatusCode());
$this->assertRegExp('/^Digest realm="TheRealmName", qop="auth", nonce="[a-zA-Z0-9\/+]+={0,2}", stale="true"$/', $response->headers->get('WWW-Authenticate'));
}
}

View File

@@ -0,0 +1,69 @@
<?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\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\EntryPoint\FormAuthenticationEntryPoint;
use Symfony\Component\HttpKernel\HttpKernelInterface;
class FormAuthenticationEntryPointTest extends TestCase
{
public function testStart()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$response = new Response();
$httpKernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils
->expects($this->once())
->method('createRedirectResponse')
->with($this->equalTo($request), $this->equalTo('/the/login/path'))
->will($this->returnValue($response))
;
$entryPoint = new FormAuthenticationEntryPoint($httpKernel, $httpUtils, '/the/login/path', false);
$this->assertEquals($response, $entryPoint->start($request));
}
public function testStartWithUseForward()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$subRequest = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$response = new Response('', 200);
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils
->expects($this->once())
->method('createRequest')
->with($this->equalTo($request), $this->equalTo('/the/login/path'))
->will($this->returnValue($subRequest))
;
$httpKernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$httpKernel
->expects($this->once())
->method('handle')
->with($this->equalTo($subRequest), $this->equalTo(HttpKernelInterface::SUB_REQUEST))
->will($this->returnValue($response))
;
$entryPoint = new FormAuthenticationEntryPoint($httpKernel, $httpUtils, '/the/login/path', true);
$entryPointResponse = $entryPoint->start($request);
$this->assertEquals($response, $entryPointResponse);
$this->assertEquals(401, $entryPointResponse->headers->get('X-Status-Code'));
}
}

View File

@@ -0,0 +1,65 @@
<?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\EntryPoint;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\EntryPoint\RetryAuthenticationEntryPoint;
use Symfony\Component\HttpFoundation\Request;
class RetryAuthenticationEntryPointTest extends TestCase
{
/**
* @dataProvider dataForStart
*/
public function testStart($httpPort, $httpsPort, $request, $expectedUrl)
{
$entryPoint = new RetryAuthenticationEntryPoint($httpPort, $httpsPort);
$response = $entryPoint->start($request);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $response);
$this->assertEquals($expectedUrl, $response->headers->get('Location'));
}
public function dataForStart()
{
if (!class_exists('Symfony\Component\HttpFoundation\Request')) {
return array(array());
}
return array(
array(
80,
443,
Request::create('http://localhost/foo/bar?baz=bat'),
'https://localhost/foo/bar?baz=bat',
),
array(
80,
443,
Request::create('https://localhost/foo/bar?baz=bat'),
'http://localhost/foo/bar?baz=bat',
),
array(
80,
123,
Request::create('http://localhost/foo/bar?baz=bat'),
'https://localhost:123/foo/bar?baz=bat',
),
array(
8080,
443,
Request::create('https://localhost/foo/bar?baz=bat'),
'http://localhost:8080/foo/bar?baz=bat',
),
);
}
}

View File

@@ -0,0 +1,253 @@
<?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\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
class AbstractPreAuthenticatedListenerTest extends TestCase
{
public function testHandleWithValidValues()
{
$userCredentials = array('TheUser', 'TheCredentials');
$request = new Request(array(), array(), array(), array(), array(), array());
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($token))
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->returnValue($token))
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWhenAuthenticationFails()
{
$userCredentials = array('TheUser', 'TheCredentials');
$request = new Request(array(), array(), array(), array(), array(), array());
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
;
$tokenStorage
->expects($this->never())
->method('setToken')
;
$exception = new AuthenticationException('Authentication failed.');
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->throwException($exception))
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWhenAuthenticationFailsWithDifferentToken()
{
$userCredentials = array('TheUser', 'TheCredentials');
$token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));
$request = new Request(array(), array(), array(), array(), array(), array());
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->never())
->method('setToken')
;
$exception = new AuthenticationException('Authentication failed.');
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->throwException($exception))
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWithASimilarAuthenticatedToken()
{
$userCredentials = array('TheUser', 'TheCredentials');
$request = new Request(array(), array(), array(), array(), array(), array());
$token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->never())
->method('authenticate')
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWithAnInvalidSimilarToken()
{
$userCredentials = array('TheUser', 'TheCredentials');
$request = new Request(array(), array(), array(), array(), array(), array());
$token = new PreAuthenticatedToken('AnotherUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo(null))
;
$exception = new AuthenticationException('Authentication failed.');
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\PreAuthenticatedToken'))
->will($this->throwException($exception))
;
$listener = $this->getMockForAbstractClass('Symfony\Component\Security\Http\Firewall\AbstractPreAuthenticatedListener', array(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
));
$listener
->expects($this->once())
->method('getPreAuthenticatedData')
->will($this->returnValue($userCredentials));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
}

View File

@@ -0,0 +1,209 @@
<?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\Security\Http\Firewall\AccessListener;
class AccessListenerTest extends TestCase
{
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
public function testHandleWhenTheAccessDecisionManagerDecidesToRefuseAccess()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array('foo' => 'bar'), null)))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->any())
->method('isAuthenticated')
->will($this->returnValue(true))
;
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$accessDecisionManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock();
$accessDecisionManager
->expects($this->once())
->method('decide')
->with($this->equalTo($token), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
->will($this->returnValue(false))
;
$listener = new AccessListener(
$tokenStorage,
$accessDecisionManager,
$accessMap,
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock()
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWhenTheTokenIsNotAuthenticated()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array('foo' => 'bar'), null)))
;
$notAuthenticatedToken = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$notAuthenticatedToken
->expects($this->any())
->method('isAuthenticated')
->will($this->returnValue(false))
;
$authenticatedToken = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$authenticatedToken
->expects($this->any())
->method('isAuthenticated')
->will($this->returnValue(true))
;
$authManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authManager
->expects($this->once())
->method('authenticate')
->with($this->equalTo($notAuthenticatedToken))
->will($this->returnValue($authenticatedToken))
;
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($notAuthenticatedToken))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($authenticatedToken))
;
$accessDecisionManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock();
$accessDecisionManager
->expects($this->once())
->method('decide')
->with($this->equalTo($authenticatedToken), $this->equalTo(array('foo' => 'bar')), $this->equalTo($request))
->will($this->returnValue(true))
;
$listener = new AccessListener(
$tokenStorage,
$accessDecisionManager,
$accessMap,
$authManager
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWhenThereIsNoAccessMapEntryMatchingTheRequest()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(null, null)))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->never())
->method('isAuthenticated')
;
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$listener = new AccessListener(
$tokenStorage,
$this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock(),
$accessMap,
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock()
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testHandleWhenTheSecurityTokenStorageHasNoToken()
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
;
$listener = new AccessListener(
$tokenStorage,
$this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock()
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$listener->handle($event);
}
}

View File

@@ -0,0 +1,88 @@
<?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\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Http\Firewall\AnonymousAuthenticationListener;
class AnonymousAuthenticationListenerTest extends TestCase
{
public function testHandleWithTokenStorageHavingAToken()
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
;
$tokenStorage
->expects($this->never())
->method('setToken')
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->never())
->method('authenticate')
;
$listener = new AnonymousAuthenticationListener($tokenStorage, 'TheSecret', null, $authenticationManager);
$listener->handle($this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock());
}
public function testHandleWithTokenStorageHavingNoToken()
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
;
$anonymousToken = new AnonymousToken('TheSecret', 'anon.', array());
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->callback(function ($token) {
return 'TheSecret' === $token->getSecret();
}))
->will($this->returnValue($anonymousToken))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($anonymousToken)
;
$listener = new AnonymousAuthenticationListener($tokenStorage, 'TheSecret', null, $authenticationManager);
$listener->handle($this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock());
}
public function testHandledEventIsLogged()
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$logger = $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
$logger->expects($this->once())
->method('info')
->with('Populated the TokenStorage with an anonymous Token.')
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new AnonymousAuthenticationListener($tokenStorage, 'TheSecret', $logger, $authenticationManager);
$listener->handle($this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock());
}
}

View File

@@ -0,0 +1,250 @@
<?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\Security\Core\Authentication\Token\PreAuthenticatedToken;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\BasicAuthenticationListener;
use Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager;
class BasicAuthenticationListenerTest extends TestCase
{
public function testHandleWithValidUsernameAndPasswordServerParameters()
{
$request = new Request(array(), array(), array(), array(), array(), array(
'PHP_AUTH_USER' => 'TheUsername',
'PHP_AUTH_PW' => 'ThePassword',
));
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($token))
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->isInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken'))
->will($this->returnValue($token))
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
$this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock()
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWhenAuthenticationFails()
{
$request = new Request(array(), array(), array(), array(), array(), array(
'PHP_AUTH_USER' => 'TheUsername',
'PHP_AUTH_PW' => 'ThePassword',
));
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue(null))
;
$tokenStorage
->expects($this->never())
->method('setToken')
;
$response = new Response();
$authenticationEntryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$authenticationEntryPoint
->expects($this->any())
->method('start')
->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
->will($this->returnValue($response))
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
new AuthenticationProviderManager(array($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock())),
'TheProviderKey',
$authenticationEntryPoint
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$event
->expects($this->once())
->method('setResponse')
->with($this->equalTo($response))
;
$listener->handle($event);
}
public function testHandleWithNoUsernameServerParameter()
{
$request = new Request();
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->never())
->method('getToken')
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
'TheProviderKey',
$this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock()
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testHandleWithASimilarAuthenticatedToken()
{
$request = new Request(array(), array(), array(), array(), array(), array('PHP_AUTH_USER' => 'TheUsername'));
$token = new UsernamePasswordToken('TheUsername', 'ThePassword', 'TheProviderKey', array('ROLE_FOO'));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$authenticationManager
->expects($this->never())
->method('authenticate')
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
$this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock()
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage $providerKey must not be empty
*/
public function testItRequiresProviderKey()
{
new BasicAuthenticationListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock(),
'',
$this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock()
);
}
public function testHandleWithADifferentAuthenticatedToken()
{
$request = new Request(array(), array(), array(), array(), array(), array(
'PHP_AUTH_USER' => 'TheUsername',
'PHP_AUTH_PW' => 'ThePassword',
));
$token = new PreAuthenticatedToken('TheUser', 'TheCredentials', 'TheProviderKey', array('ROLE_FOO'));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->any())
->method('getToken')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->never())
->method('setToken')
;
$response = new Response();
$authenticationEntryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$authenticationEntryPoint
->expects($this->any())
->method('start')
->with($this->equalTo($request), $this->isInstanceOf('Symfony\Component\Security\Core\Exception\AuthenticationException'))
->will($this->returnValue($response))
;
$listener = new BasicAuthenticationListener(
$tokenStorage,
new AuthenticationProviderManager(array($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Provider\AuthenticationProviderInterface')->getMock())),
'TheProviderKey',
$authenticationEntryPoint
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$event
->expects($this->once())
->method('setResponse')
->with($this->equalTo($response))
;
$listener->handle($event);
}
}

View File

@@ -0,0 +1,181 @@
<?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\Security\Http\Firewall\ChannelListener;
use Symfony\Component\HttpFoundation\Response;
class ChannelListenerTest extends TestCase
{
public function testHandleWithNotSecuredRequestAndHttpChannel()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(false))
;
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'http')))
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint
->expects($this->never())
->method('start')
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$event
->expects($this->never())
->method('setResponse')
;
$listener = new ChannelListener($accessMap, $entryPoint);
$listener->handle($event);
}
public function testHandleWithSecuredRequestAndHttpsChannel()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(true))
;
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'https')))
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint
->expects($this->never())
->method('start')
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$event
->expects($this->never())
->method('setResponse')
;
$listener = new ChannelListener($accessMap, $entryPoint);
$listener->handle($event);
}
public function testHandleWithNotSecuredRequestAndHttpsChannel()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(false))
;
$response = new Response();
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'https')))
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint
->expects($this->once())
->method('start')
->with($this->equalTo($request))
->will($this->returnValue($response))
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$event
->expects($this->once())
->method('setResponse')
->with($this->equalTo($response))
;
$listener = new ChannelListener($accessMap, $entryPoint);
$listener->handle($event);
}
public function testHandleWithSecuredRequestAndHttpChannel()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$request
->expects($this->any())
->method('isSecure')
->will($this->returnValue(true))
;
$response = new Response();
$accessMap = $this->getMockBuilder('Symfony\Component\Security\Http\AccessMapInterface')->getMock();
$accessMap
->expects($this->any())
->method('getPatterns')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), 'http')))
;
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint
->expects($this->once())
->method('start')
->with($this->equalTo($request))
->will($this->returnValue($response))
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$event
->expects($this->once())
->method('setResponse')
->with($this->equalTo($response))
;
$listener = new ChannelListener($accessMap, $entryPoint);
$listener->handle($event);
}
}

View File

@@ -0,0 +1,380 @@
<?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\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpFoundation\Session\Storage\MockArraySessionStorage;
use Symfony\Component\HttpKernel\Event\FilterResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\Security\Core\Authentication\Token\AnonymousToken;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Http\Firewall\ContextListener;
use Symfony\Component\EventDispatcher\EventDispatcher;
class ContextListenerTest extends TestCase
{
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage $contextKey must not be empty
*/
public function testItRequiresContextKey()
{
new ContextListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
array(),
''
);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage User provider "stdClass" must implement "Symfony\Component\Security\Core\User\UserProviderInterface
*/
public function testUserProvidersNeedToImplementAnInterface()
{
new ContextListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
array(new \stdClass()),
'key123'
);
}
public function testOnKernelResponseWillAddSession()
{
$session = $this->runSessionOnKernelResponse(
new UsernamePasswordToken('test1', 'pass1', 'phpunit'),
null
);
$token = unserialize($session->get('_security_session'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $token);
$this->assertEquals('test1', $token->getUsername());
}
public function testOnKernelResponseWillReplaceSession()
{
$session = $this->runSessionOnKernelResponse(
new UsernamePasswordToken('test1', 'pass1', 'phpunit'),
'C:10:"serialized"'
);
$token = unserialize($session->get('_security_session'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $token);
$this->assertEquals('test1', $token->getUsername());
}
public function testOnKernelResponseWillRemoveSession()
{
$session = $this->runSessionOnKernelResponse(
null,
'C:10:"serialized"'
);
$this->assertFalse($session->has('_security_session'));
}
public function testOnKernelResponseWillRemoveSessionOnAnonymousToken()
{
$session = $this->runSessionOnKernelResponse(new AnonymousToken('secret', 'anon.'), 'C:10:"serialized"');
$this->assertFalse($session->has('_security_session'));
}
public function testOnKernelResponseWithoutSession()
{
$tokenStorage = new TokenStorage();
$tokenStorage->setToken(new UsernamePasswordToken('test1', 'pass1', 'phpunit'));
$request = new Request();
$session = new Session(new MockArraySessionStorage());
$request->setSession($session);
$event = new FilterResponseEvent(
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
$request,
HttpKernelInterface::MASTER_REQUEST,
new Response()
);
$listener = new ContextListener($tokenStorage, array(), 'session', null, new EventDispatcher());
$listener->onKernelResponse($event);
$this->assertTrue($session->isStarted());
}
public function testOnKernelResponseWithoutSessionNorToken()
{
$request = new Request();
$session = new Session(new MockArraySessionStorage());
$request->setSession($session);
$event = new FilterResponseEvent(
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
$request,
HttpKernelInterface::MASTER_REQUEST,
new Response()
);
$listener = new ContextListener(new TokenStorage(), array(), 'session', null, new EventDispatcher());
$listener->onKernelResponse($event);
$this->assertFalse($session->isStarted());
}
/**
* @dataProvider provideInvalidToken
*/
public function testInvalidTokenInSession($token)
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->disableOriginalConstructor()
->getMock();
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
$request->expects($this->any())
->method('hasPreviousSession')
->will($this->returnValue(true));
$request->expects($this->any())
->method('getSession')
->will($this->returnValue($session));
$session->expects($this->any())
->method('get')
->with('_security_key123')
->will($this->returnValue($token));
$tokenStorage->expects($this->once())
->method('setToken')
->with(null);
$listener = new ContextListener($tokenStorage, array(), 'key123');
$listener->handle($event);
}
public function provideInvalidToken()
{
return array(
array(serialize(new \__PHP_Incomplete_Class())),
array(serialize(null)),
array(null),
);
}
public function testHandleAddsKernelResponseListener()
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->disableOriginalConstructor()
->getMock();
$listener = new ContextListener($tokenStorage, array(), 'key123', null, $dispatcher);
$event->expects($this->any())
->method('isMasterRequest')
->will($this->returnValue(true));
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock()));
$dispatcher->expects($this->once())
->method('addListener')
->with(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$listener->handle($event);
}
public function testOnKernelResponseListenerRemovesItself()
{
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent')
->disableOriginalConstructor()
->getMock();
$listener = new ContextListener($tokenStorage, array(), 'key123', null, $dispatcher);
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request->expects($this->any())
->method('hasSession')
->will($this->returnValue(true));
$event->expects($this->any())
->method('isMasterRequest')
->will($this->returnValue(true));
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request));
$dispatcher->expects($this->once())
->method('removeListener')
->with(KernelEvents::RESPONSE, array($listener, 'onKernelResponse'));
$listener->onKernelResponse($event);
}
public function testHandleRemovesTokenIfNoPreviousSessionWasFound()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$request->expects($this->any())->method('hasPreviousSession')->will($this->returnValue(false));
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage->expects($this->once())->method('setToken')->with(null);
$listener = new ContextListener($tokenStorage, array(), 'key123');
$listener->handle($event);
}
public function testTryAllUserProvidersUntilASupportingUserProviderIsFound()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, array(new NotSupportingUserProvider(), new SupportingUserProvider($refreshedUser)));
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
}
public function testNextSupportingUserProviderIsTriedIfPreviousSupportingUserProviderDidNotLoadTheUser()
{
$tokenStorage = new TokenStorage();
$refreshedUser = new User('foobar', 'baz');
$this->handleEventWithPreviousSession($tokenStorage, array(new SupportingUserProvider(), new SupportingUserProvider($refreshedUser)));
$this->assertSame($refreshedUser, $tokenStorage->getToken()->getUser());
}
public function testTokenIsSetToNullIfNoUserWasLoadedByTheRegisteredUserProviders()
{
$tokenStorage = new TokenStorage();
$this->handleEventWithPreviousSession($tokenStorage, array(new NotSupportingUserProvider(), new SupportingUserProvider()));
$this->assertNull($tokenStorage->getToken());
}
/**
* @expectedException \RuntimeException
*/
public function testRuntimeExceptionIsThrownIfNoSupportingUserProviderWasRegistered()
{
$this->handleEventWithPreviousSession(new TokenStorage(), array(new NotSupportingUserProvider(), new NotSupportingUserProvider()));
}
protected function runSessionOnKernelResponse($newToken, $original = null)
{
$session = new Session(new MockArraySessionStorage());
if ($original !== null) {
$session->set('_security_session', $original);
}
$tokenStorage = new TokenStorage();
$tokenStorage->setToken($newToken);
$request = new Request();
$request->setSession($session);
$request->cookies->set('MOCKSESSID', true);
$event = new FilterResponseEvent(
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
$request,
HttpKernelInterface::MASTER_REQUEST,
new Response()
);
$listener = new ContextListener($tokenStorage, array(), 'session', null, new EventDispatcher());
$listener->onKernelResponse($event);
return $session;
}
private function handleEventWithPreviousSession(TokenStorageInterface $tokenStorage, array $userProviders)
{
$session = new Session(new MockArraySessionStorage());
$session->set('_security_context_key', serialize(new UsernamePasswordToken(new User('foo', 'bar'), '', 'context_key')));
$request = new Request();
$request->setSession($session);
$request->cookies->set('MOCKSESSID', true);
$listener = new ContextListener($tokenStorage, $userProviders, 'context_key');
$listener->handle(new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST));
}
}
class NotSupportingUserProvider implements UserProviderInterface
{
public function loadUserByUsername($username)
{
throw new UsernameNotFoundException();
}
public function refreshUser(UserInterface $user)
{
throw new UnsupportedUserException();
}
public function supportsClass($class)
{
return false;
}
}
class SupportingUserProvider implements UserProviderInterface
{
private $refreshedUser;
public function __construct(User $refreshedUser = null)
{
$this->refreshedUser = $refreshedUser;
}
public function loadUserByUsername($username)
{
}
public function refreshUser(UserInterface $user)
{
if (!$user instanceof User) {
throw new UnsupportedUserException();
}
if (null === $this->refreshedUser) {
throw new UsernameNotFoundException();
}
return $this->refreshedUser;
}
public function supportsClass($class)
{
return 'Symfony\Component\Security\Core\User\User' === $class;
}
}

View File

@@ -0,0 +1,80 @@
<?php
namespace Symfony\Component\Security\Http\Tests\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Http\EntryPoint\DigestAuthenticationEntryPoint;
use Symfony\Component\Security\Http\Firewall\DigestAuthenticationListener;
class DigestAuthenticationListenerTest extends TestCase
{
public function testHandleWithValidDigest()
{
$time = microtime(true) + 1000;
$secret = 'ThisIsASecret';
$nonce = base64_encode($time.':'.md5($time.':'.$secret));
$username = 'user';
$password = 'password';
$realm = 'Welcome, robot!';
$cnonce = 'MDIwODkz';
$nc = '00000001';
$qop = 'auth';
$uri = '/path/info?p1=5&p2=5';
$serverDigest = $this->calculateServerDigest($username, $realm, $password, $nc, $nonce, $cnonce, $qop, 'GET', $uri);
$digestData =
'username="'.$username.'", realm="'.$realm.'", nonce="'.$nonce.'", '.
'uri="'.$uri.'", cnonce="'.$cnonce.'", nc='.$nc.', qop="'.$qop.'", '.
'response="'.$serverDigest.'"'
;
$request = new Request(array(), array(), array(), array(), array(), array('PHP_AUTH_DIGEST' => $digestData));
$entryPoint = new DigestAuthenticationEntryPoint($realm, $secret);
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user->method('getPassword')->willReturn($password);
$providerKey = 'TheProviderKey';
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo(new UsernamePasswordToken($user, $password, $providerKey)))
;
$userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$userProvider->method('loadUserByUsername')->willReturn($user);
$listener = new DigestAuthenticationListener($tokenStorage, $userProvider, $providerKey, $entryPoint);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
private function calculateServerDigest($username, $realm, $password, $nc, $nonce, $cnonce, $qop, $method, $uri)
{
$response = md5(
md5($username.':'.$realm.':'.$password).':'.$nonce.':'.$nc.':'.$cnonce.':'.$qop.':'.md5($method.':'.$uri)
);
return sprintf('username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%s, qop="%s", response="%s"',
$username, $realm, $nonce, $uri, $cnonce, $nc, $qop, $response
);
}
}

View File

@@ -0,0 +1,185 @@
<?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\Security\Http\Firewall\DigestData;
class DigestDataTest extends TestCase
{
public function testGetResponse()
{
$digestAuth = new DigestData(
'username="user", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('b52938fc9e6d7c01be7702ece9031b42', $digestAuth->getResponse());
}
public function testGetUsername()
{
$digestAuth = new DigestData(
'username="user", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('user', $digestAuth->getUsername());
}
public function testGetUsernameWithQuote()
{
$digestAuth = new DigestData(
'username="\"user\"", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('"user"', $digestAuth->getUsername());
}
public function testGetUsernameWithQuoteAndEscape()
{
$digestAuth = new DigestData(
'username="\"u\\\\\"ser\"", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('"u\\"ser"', $digestAuth->getUsername());
}
public function testGetUsernameWithSingleQuote()
{
$digestAuth = new DigestData(
'username="\"u\'ser\"", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('"u\'ser"', $digestAuth->getUsername());
}
public function testGetUsernameWithSingleQuoteAndEscape()
{
$digestAuth = new DigestData(
'username="\"u\\\'ser\"", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('"u\\\'ser"', $digestAuth->getUsername());
}
public function testGetUsernameWithEscape()
{
$digestAuth = new DigestData(
'username="\"u\\ser\"", realm="Welcome, robot!", '.
'nonce="MTM0NzMyMTgyMy42NzkzOmRlZjM4NmIzOGNjMjE0OWJiNDU0MDAxNzJmYmM1MmZl", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$this->assertEquals('"u\\ser"', $digestAuth->getUsername());
}
/**
* @group time-sensitive
*/
public function testValidateAndDecode()
{
$time = microtime(true);
$key = 'ThisIsAKey';
$nonce = base64_encode($time.':'.md5($time.':'.$key));
$digestAuth = new DigestData(
'username="user", realm="Welcome, robot!", nonce="'.$nonce.'", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$digestAuth->validateAndDecode($key, 'Welcome, robot!');
sleep(1);
$this->assertTrue($digestAuth->isNonceExpired());
}
public function testCalculateServerDigest()
{
$this->calculateServerDigest('user', 'Welcome, robot!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
}
public function testCalculateServerDigestWithQuote()
{
$this->calculateServerDigest('\"user\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
}
public function testCalculateServerDigestWithQuoteAndEscape()
{
$this->calculateServerDigest('\"u\\\\\"ser\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
}
public function testCalculateServerDigestEscape()
{
$this->calculateServerDigest('\"u\\ser\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
$this->calculateServerDigest('\"u\\ser\\\\\"', 'Welcome, \"robot\"!', 'pass,word=password', 'ThisIsAKey', '00000001', 'MDIwODkz', 'auth', 'GET', '/path/info?p1=5&p2=5');
}
public function testIsNonceExpired()
{
$time = microtime(true) + 10;
$key = 'ThisIsAKey';
$nonce = base64_encode($time.':'.md5($time.':'.$key));
$digestAuth = new DigestData(
'username="user", realm="Welcome, robot!", nonce="'.$nonce.'", '.
'uri="/path/info?p1=5&p2=5", cnonce="MDIwODkz", nc=00000001, qop="auth", '.
'response="b52938fc9e6d7c01be7702ece9031b42"'
);
$digestAuth->validateAndDecode($key, 'Welcome, robot!');
$this->assertFalse($digestAuth->isNonceExpired());
}
protected function setUp()
{
class_exists('Symfony\Component\Security\Http\Firewall\DigestAuthenticationListener', true);
}
private function calculateServerDigest($username, $realm, $password, $key, $nc, $cnonce, $qop, $method, $uri)
{
$time = microtime(true);
$nonce = base64_encode($time.':'.md5($time.':'.$key));
$response = md5(
md5($username.':'.$realm.':'.$password).':'.$nonce.':'.$nc.':'.$cnonce.':'.$qop.':'.md5($method.':'.$uri)
);
$digest = sprintf('username="%s", realm="%s", nonce="%s", uri="%s", cnonce="%s", nc=%s, qop="%s", response="%s"',
$username, $realm, $nonce, $uri, $cnonce, $nc, $qop, $response
);
$digestAuth = new DigestData($digest);
$this->assertEquals($digestAuth->getResponse(), $digestAuth->calculateServerDigest($password, $method));
}
}

View File

@@ -0,0 +1,199 @@
<?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\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface;
use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
use Symfony\Component\Security\Http\Firewall\ExceptionListener;
use Symfony\Component\Security\Http\HttpUtils;
class ExceptionListenerTest extends TestCase
{
/**
* @dataProvider getAuthenticationExceptionProvider
*/
public function testAuthenticationExceptionWithoutEntryPoint(\Exception $exception, \Exception $eventException = null)
{
$event = $this->createEvent($exception);
$listener = $this->createExceptionListener();
$listener->onKernelException($event);
$this->assertNull($event->getResponse());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException());
}
/**
* @dataProvider getAuthenticationExceptionProvider
*/
public function testAuthenticationExceptionWithEntryPoint(\Exception $exception, \Exception $eventException = null)
{
$event = $this->createEvent($exception = new AuthenticationException());
$listener = $this->createExceptionListener(null, null, null, $this->createEntryPoint());
$listener->onKernelException($event);
$this->assertEquals('OK', $event->getResponse()->getContent());
$this->assertSame($exception, $event->getException());
}
public function getAuthenticationExceptionProvider()
{
return array(
array(new AuthenticationException()),
array(new \LogicException('random', 0, $e = new AuthenticationException()), $e),
array(new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AuthenticationException())), $e),
array(new \LogicException('random', 0, $e = new AuthenticationException('embed', 0, new AccessDeniedException())), $e),
array(new AuthenticationException('random', 0, new \LogicException())),
);
}
public function testExceptionWhenEntryPointReturnsBadValue()
{
$event = $this->createEvent(new AuthenticationException());
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint->expects($this->once())->method('start')->will($this->returnValue('NOT A RESPONSE'));
$listener = $this->createExceptionListener(null, null, null, $entryPoint);
$listener->onKernelException($event);
// the exception has been replaced by our LogicException
$this->assertInstanceOf('LogicException', $event->getException());
$this->assertStringEndsWith('start() method must return a Response object (string returned)', $event->getException()->getMessage());
}
/**
* @dataProvider getAccessDeniedExceptionProvider
*/
public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandlerAndWithoutErrorPage(\Exception $exception, \Exception $eventException = null)
{
$event = $this->createEvent($exception);
$listener = $this->createExceptionListener(null, $this->createTrustResolver(true));
$listener->onKernelException($event);
$this->assertNull($event->getResponse());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
}
/**
* @dataProvider getAccessDeniedExceptionProvider
*/
public function testAccessDeniedExceptionFullFledgedAndWithoutAccessDeniedHandlerAndWithErrorPage(\Exception $exception, \Exception $eventException = null)
{
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
$kernel->expects($this->once())->method('handle')->will($this->returnValue(new Response('error')));
$event = $this->createEvent($exception, $kernel);
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils->expects($this->once())->method('createRequest')->will($this->returnValue(Request::create('/error')));
$listener = $this->createExceptionListener(null, $this->createTrustResolver(true), $httpUtils, null, '/error');
$listener->onKernelException($event);
$this->assertEquals('error', $event->getResponse()->getContent());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
}
/**
* @dataProvider getAccessDeniedExceptionProvider
*/
public function testAccessDeniedExceptionFullFledgedAndWithAccessDeniedHandlerAndWithoutErrorPage(\Exception $exception, \Exception $eventException = null)
{
$event = $this->createEvent($exception);
$accessDeniedHandler = $this->getMockBuilder('Symfony\Component\Security\Http\Authorization\AccessDeniedHandlerInterface')->getMock();
$accessDeniedHandler->expects($this->once())->method('handle')->will($this->returnValue(new Response('error')));
$listener = $this->createExceptionListener(null, $this->createTrustResolver(true), null, null, null, $accessDeniedHandler);
$listener->onKernelException($event);
$this->assertEquals('error', $event->getResponse()->getContent());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
}
/**
* @dataProvider getAccessDeniedExceptionProvider
*/
public function testAccessDeniedExceptionNotFullFledged(\Exception $exception, \Exception $eventException = null)
{
$event = $this->createEvent($exception);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$tokenStorage->expects($this->once())->method('getToken')->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()));
$listener = $this->createExceptionListener($tokenStorage, $this->createTrustResolver(false), null, $this->createEntryPoint());
$listener->onKernelException($event);
$this->assertEquals('OK', $event->getResponse()->getContent());
$this->assertSame(null === $eventException ? $exception : $eventException, $event->getException()->getPrevious());
}
public function getAccessDeniedExceptionProvider()
{
return array(
array(new AccessDeniedException()),
array(new \LogicException('random', 0, $e = new AccessDeniedException()), $e),
array(new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AccessDeniedException())), $e),
array(new \LogicException('random', 0, $e = new AccessDeniedException('embed', new AuthenticationException())), $e),
array(new AccessDeniedException('random', new \LogicException())),
);
}
private function createEntryPoint()
{
$entryPoint = $this->getMockBuilder('Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface')->getMock();
$entryPoint->expects($this->once())->method('start')->will($this->returnValue(new Response('OK')));
return $entryPoint;
}
private function createTrustResolver($fullFledged)
{
$trustResolver = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface')->getMock();
$trustResolver->expects($this->once())->method('isFullFledged')->will($this->returnValue($fullFledged));
return $trustResolver;
}
private function createEvent(\Exception $exception, $kernel = null)
{
if (null === $kernel) {
$kernel = $this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock();
}
return new GetResponseForExceptionEvent($kernel, Request::create('/'), HttpKernelInterface::MASTER_REQUEST, $exception);
}
private function createExceptionListener(TokenStorageInterface $tokenStorage = null, AuthenticationTrustResolverInterface $trustResolver = null, HttpUtils $httpUtils = null, AuthenticationEntryPointInterface $authenticationEntryPoint = null, $errorPage = null, AccessDeniedHandlerInterface $accessDeniedHandler = null)
{
return new ExceptionListener(
$tokenStorage ?: $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
$trustResolver ?: $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationTrustResolverInterface')->getMock(),
$httpUtils ?: $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock(),
'key',
$authenticationEntryPoint,
$errorPage,
$accessDeniedHandler
);
}
}

View File

@@ -0,0 +1,236 @@
<?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\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\LogoutListener;
class LogoutListenerTest extends TestCase
{
public function testHandleUnmatchedPath()
{
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener();
list($event, $request) = $this->getGetResponseEvent();
$event->expects($this->never())
->method('setResponse');
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(false));
$listener->handle($event);
}
public function testHandleMatchedPathWithSuccessHandlerAndCsrfValidation()
{
$successHandler = $this->getSuccessHandler();
$tokenManager = $this->getTokenManager();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener($successHandler, $tokenManager);
list($event, $request) = $this->getGetResponseEvent();
$request->query->set('_csrf_token', 'token');
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
$tokenManager->expects($this->once())
->method('isTokenValid')
->will($this->returnValue(true));
$successHandler->expects($this->once())
->method('onLogoutSuccess')
->with($request)
->will($this->returnValue($response = new Response()));
$tokenStorage->expects($this->once())
->method('getToken')
->will($this->returnValue($token = $this->getToken()));
$handler = $this->getHandler();
$handler->expects($this->once())
->method('logout')
->with($request, $response, $token);
$tokenStorage->expects($this->once())
->method('setToken')
->with(null);
$event->expects($this->once())
->method('setResponse')
->with($response);
$listener->addHandler($handler);
$listener->handle($event);
}
public function testHandleMatchedPathWithoutSuccessHandlerAndCsrfValidation()
{
$successHandler = $this->getSuccessHandler();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener($successHandler);
list($event, $request) = $this->getGetResponseEvent();
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
$successHandler->expects($this->once())
->method('onLogoutSuccess')
->with($request)
->will($this->returnValue($response = new Response()));
$tokenStorage->expects($this->once())
->method('getToken')
->will($this->returnValue($token = $this->getToken()));
$handler = $this->getHandler();
$handler->expects($this->once())
->method('logout')
->with($request, $response, $token);
$tokenStorage->expects($this->once())
->method('setToken')
->with(null);
$event->expects($this->once())
->method('setResponse')
->with($response);
$listener->addHandler($handler);
$listener->handle($event);
}
/**
* @expectedException \RuntimeException
*/
public function testSuccessHandlerReturnsNonResponse()
{
$successHandler = $this->getSuccessHandler();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener($successHandler);
list($event, $request) = $this->getGetResponseEvent();
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
$successHandler->expects($this->once())
->method('onLogoutSuccess')
->with($request)
->will($this->returnValue(null));
$listener->handle($event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\LogoutException
*/
public function testCsrfValidationFails()
{
$tokenManager = $this->getTokenManager();
list($listener, $tokenStorage, $httpUtils, $options) = $this->getListener(null, $tokenManager);
list($event, $request) = $this->getGetResponseEvent();
$request->query->set('_csrf_token', 'token');
$httpUtils->expects($this->once())
->method('checkRequestPath')
->with($request, $options['logout_path'])
->will($this->returnValue(true));
$tokenManager->expects($this->once())
->method('isTokenValid')
->will($this->returnValue(false));
$listener->handle($event);
}
private function getTokenManager()
{
return $this->getMockBuilder('Symfony\Component\Security\Csrf\CsrfTokenManagerInterface')->getMock();
}
private function getTokenStorage()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
}
private function getGetResponseEvent()
{
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())
->method('getRequest')
->will($this->returnValue($request = new Request()));
return array($event, $request);
}
private function getHandler()
{
return $this->getMockBuilder('Symfony\Component\Security\Http\Logout\LogoutHandlerInterface')->getMock();
}
private function getHttpUtils()
{
return $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')
->disableOriginalConstructor()
->getMock();
}
private function getListener($successHandler = null, $tokenManager = null)
{
$listener = new LogoutListener(
$tokenStorage = $this->getTokenStorage(),
$httpUtils = $this->getHttpUtils(),
$successHandler ?: $this->getSuccessHandler(),
$options = array(
'csrf_parameter' => '_csrf_token',
'csrf_token_id' => 'logout',
'logout_path' => '/logout',
'target_url' => '/',
),
$tokenManager
);
return array($listener, $tokenStorage, $httpUtils, $options);
}
private function getSuccessHandler()
{
return $this->getMockBuilder('Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface')->getMock();
}
private function getToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
}
}

View File

@@ -0,0 +1,416 @@
<?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\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Firewall\RememberMeListener;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\SecurityEvents;
class RememberMeListenerTest extends TestCase
{
public function testOnCoreSecurityDoesNotTryToPopulateNonEmptyTokenStorage()
{
list($listener, $tokenStorage) = $this->getListener();
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
;
$tokenStorage
->expects($this->never())
->method('setToken')
;
$this->assertNull($listener->handle($this->getGetResponseEvent()));
}
public function testOnCoreSecurityDoesNothingWhenNoCookieIsSet()
{
list($listener, $tokenStorage, $service) = $this->getListener();
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue(null))
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
;
$this->assertNull($listener->handle($event));
}
public function testOnCoreSecurityIgnoresAuthenticationExceptionThrownByAuthenticationManagerImplementation()
{
list($listener, $tokenStorage, $service, $manager) = $this->getListener();
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
;
$service
->expects($this->once())
->method('loginFail')
;
$exception = new AuthenticationException('Authentication failed.');
$manager
->expects($this->once())
->method('authenticate')
->will($this->throwException($exception))
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
;
$listener->handle($event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationException
* @expectedExceptionMessage Authentication failed.
*/
public function testOnCoreSecurityIgnoresAuthenticationOptionallyRethrowsExceptionThrownAuthenticationManagerImplementation()
{
list($listener, $tokenStorage, $service, $manager) = $this->getListener(false, false);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock()))
;
$service
->expects($this->once())
->method('loginFail')
;
$exception = new AuthenticationException('Authentication failed.');
$manager
->expects($this->once())
->method('authenticate')
->will($this->throwException($exception))
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
;
$listener->handle($event);
}
public function testOnCoreSecurity()
{
list($listener, $tokenStorage, $service, $manager) = $this->getListener();
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($token))
;
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue(new Request()))
;
$listener->handle($event);
}
public function testSessionStrategy()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher, $sessionStrategy) = $this->getListener(false, true, true);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($token))
;
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
;
$session = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session
->expects($this->once())
->method('isStarted')
->will($this->returnValue(true))
;
$request = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Request')->getMock();
$request
->expects($this->once())
->method('hasSession')
->will($this->returnValue(true))
;
$request
->expects($this->once())
->method('getSession')
->will($this->returnValue($session))
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue($request))
;
$sessionStrategy
->expects($this->once())
->method('onAuthentication')
->will($this->returnValue(null))
;
$listener->handle($event);
}
public function testSessionIsMigratedByDefault()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher, $sessionStrategy) = $this->getListener(false, true, false);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($token))
;
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
;
$session = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session
->expects($this->once())
->method('isStarted')
->will($this->returnValue(true))
;
$session
->expects($this->once())
->method('migrate')
;
$request = $this->getMockBuilder('\Symfony\Component\HttpFoundation\Request')->getMock();
$request
->expects($this->any())
->method('hasSession')
->will($this->returnValue(true))
;
$request
->expects($this->any())
->method('getSession')
->will($this->returnValue($session))
;
$event = $this->getGetResponseEvent();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function testOnCoreSecurityInteractiveLoginEventIsDispatchedIfDispatcherIsPresent()
{
list($listener, $tokenStorage, $service, $manager, , $dispatcher) = $this->getListener(true);
$tokenStorage
->expects($this->once())
->method('getToken')
->will($this->returnValue(null))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service
->expects($this->once())
->method('autoLogin')
->will($this->returnValue($token))
;
$tokenStorage
->expects($this->once())
->method('setToken')
->with($this->equalTo($token))
;
$manager
->expects($this->once())
->method('authenticate')
->will($this->returnValue($token))
;
$event = $this->getGetResponseEvent();
$request = new Request();
$event
->expects($this->once())
->method('getRequest')
->will($this->returnValue($request))
;
$dispatcher
->expects($this->once())
->method('dispatch')
->with(
SecurityEvents::INTERACTIVE_LOGIN,
$this->isInstanceOf('Symfony\Component\Security\Http\Event\InteractiveLoginEvent')
)
;
$listener->handle($event);
}
protected function getGetResponseEvent()
{
return $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
}
protected function getFilterResponseEvent()
{
return $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent')->disableOriginalConstructor()->getMock();
}
protected function getListener($withDispatcher = false, $catchExceptions = true, $withSessionStrategy = false)
{
$listener = new RememberMeListener(
$tokenStorage = $this->getTokenStorage(),
$service = $this->getService(),
$manager = $this->getManager(),
$logger = $this->getLogger(),
$dispatcher = ($withDispatcher ? $this->getDispatcher() : null),
$catchExceptions,
$sessionStrategy = ($withSessionStrategy ? $this->getSessionStrategy() : null)
);
return array($listener, $tokenStorage, $service, $manager, $logger, $dispatcher, $sessionStrategy);
}
protected function getLogger()
{
return $this->getMockBuilder('Psr\Log\LoggerInterface')->getMock();
}
protected function getManager()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
}
protected function getService()
{
return $this->getMockBuilder('Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface')->getMock();
}
protected function getTokenStorage()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
}
protected function getDispatcher()
{
return $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
}
private function getSessionStrategy()
{
return $this->getMockBuilder('\Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface')->getMock();
}
}

View File

@@ -0,0 +1,92 @@
<?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\Security\Http\Firewall\RemoteUserAuthenticationListener;
class RemoteUserAuthenticationListenerTest extends TestCase
{
public function testGetPreAuthenticatedData()
{
$serverVars = array(
'REMOTE_USER' => 'TheUser',
);
$request = new Request(array(), array(), array(), array(), array(), $serverVars);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new RemoteUserAuthenticationListener(
$tokenStorage,
$authenticationManager,
'TheProviderKey'
);
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, array('TheUser', null));
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testGetPreAuthenticatedDataNoUser()
{
$request = new Request(array(), array(), array(), array(), array(), array());
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new RemoteUserAuthenticationListener(
$tokenStorage,
$authenticationManager,
'TheProviderKey'
);
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
}
public function testGetPreAuthenticatedDataWithDifferentKeys()
{
$userCredentials = array('TheUser', null);
$request = new Request(array(), array(), array(), array(), array(), array(
'TheUserKey' => 'TheUser',
));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new RemoteUserAuthenticationListener(
$tokenStorage,
$authenticationManager,
'TheProviderKey',
'TheUserKey'
);
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, $userCredentials);
}
}

View File

@@ -0,0 +1,129 @@
<?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\Security\Core\Exception\AuthenticationException;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Http\Firewall\SimplePreAuthenticationListener;
use Symfony\Component\Security\Http\SecurityEvents;
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))
->will($this->returnValue($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'))
->will($this->returnValue($this->token))
;
$loginEvent = new InteractiveLoginEvent($this->request, $this->token);
$this->dispatcher
->expects($this->once())
->method('dispatch')
->with($this->equalTo(SecurityEvents::INTERACTIVE_LOGIN), $this->equalTo($loginEvent))
;
$listener = new SimplePreAuthenticationListener($this->tokenStorage, $this->authenticationManager, 'secured_area', $simpleAuthenticator, $this->logger, $this->dispatcher);
$listener->handle($this->event);
}
public function testHandlecatchAuthenticationException()
{
$exception = new AuthenticationException('Authentication failed.');
$this->authenticationManager
->expects($this->once())
->method('authenticate')
->with($this->equalTo($this->token))
->will($this->throwException($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'))
->will($this->returnValue($this->token))
;
$listener = new SimplePreAuthenticationListener($this->tokenStorage, $this->authenticationManager, 'secured_area', $simpleAuthenticator, $this->logger, $this->dispatcher);
$listener->handle($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(array(), array(), array(), array(), array(), array());
$this->event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$this->event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($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;
}
}

View File

@@ -0,0 +1,230 @@
<?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\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Role\SwitchUserRole;
use Symfony\Component\Security\Core\User\User;
use Symfony\Component\Security\Http\Event\SwitchUserEvent;
use Symfony\Component\Security\Http\Firewall\SwitchUserListener;
use Symfony\Component\Security\Http\SecurityEvents;
class SwitchUserListenerTest extends TestCase
{
private $tokenStorage;
private $userProvider;
private $userChecker;
private $accessDecisionManager;
private $request;
private $event;
protected function setUp()
{
$this->tokenStorage = new TokenStorage();
$this->userProvider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$this->userChecker = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserCheckerInterface')->getMock();
$this->accessDecisionManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authorization\AccessDecisionManagerInterface')->getMock();
$this->request = new Request();
$this->event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $this->request, HttpKernelInterface::MASTER_REQUEST);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage $providerKey must not be empty
*/
public function testProviderKeyIsRequired()
{
new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, '', $this->accessDecisionManager);
}
public function testEventIsIgnoredIfUsernameIsNotPassedWithTheRequest()
{
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertNull($this->event->getResponse());
$this->assertNull($this->tokenStorage->getToken());
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testExitUserThrowsAuthenticationExceptionIfNoCurrentToken()
{
$this->tokenStorage->setToken(null);
$this->request->query->set('_switch_user', '_exit');
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AuthenticationCredentialsNotFoundException
*/
public function testExitUserThrowsAuthenticationExceptionIfOriginalTokenCannotBeFound()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', '_exit');
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
}
public function testExitUserUpdatesToken()
{
$originalToken = new UsernamePasswordToken('username', '', 'key', array());
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', array(new SwitchUserRole('ROLE_PREVIOUS', $originalToken))));
$this->request->query->set('_switch_user', '_exit');
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertSame(array(), $this->request->query->all());
$this->assertSame('', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\HttpFoundation\RedirectResponse', $this->event->getResponse());
$this->assertSame($this->request->getUri(), $this->event->getResponse()->getTargetUrl());
$this->assertSame($originalToken, $this->tokenStorage->getToken());
}
public function testExitUserDispatchesEventWithRefreshedUser()
{
$originalUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$refreshedUser = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$this
->userProvider
->expects($this->any())
->method('refreshUser')
->with($originalUser)
->willReturn($refreshedUser);
$originalToken = new UsernamePasswordToken($originalUser, '', 'key');
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', array(new SwitchUserRole('ROLE_PREVIOUS', $originalToken))));
$this->request->query->set('_switch_user', '_exit');
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->once())
->method('dispatch')
->with(SecurityEvents::SWITCH_USER, $this->callback(function (SwitchUserEvent $event) use ($refreshedUser) {
return $event->getTargetUser() === $refreshedUser;
}))
;
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager, null, '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', $dispatcher);
$listener->handle($this->event);
}
public function testExitUserDoesNotDispatchEventWithStringUser()
{
$originalUser = 'anon.';
$this
->userProvider
->expects($this->never())
->method('refreshUser');
$originalToken = new UsernamePasswordToken($originalUser, '', 'key');
$this->tokenStorage->setToken(new UsernamePasswordToken('username', '', 'key', array(new SwitchUserRole('ROLE_PREVIOUS', $originalToken))));
$this->request->query->set('_switch_user', '_exit');
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$dispatcher
->expects($this->never())
->method('dispatch')
;
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager, null, '_switch_user', 'ROLE_ALLOWED_TO_SWITCH', $dispatcher);
$listener->handle($this->event);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\AccessDeniedException
*/
public function testSwitchUserIsDisallowed()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
->will($this->returnValue(false));
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
}
public function testSwitchUser()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$user = new User('username', 'password', array());
$this->tokenStorage->setToken($token);
$this->request->query->set('_switch_user', 'kuba');
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
->will($this->returnValue(true));
$this->userProvider->expects($this->once())
->method('loadUserByUsername')->with('kuba')
->will($this->returnValue($user));
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($user);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertSame(array(), $this->request->query->all());
$this->assertSame('', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $this->tokenStorage->getToken());
}
public function testSwitchUserKeepsOtherQueryStringParameters()
{
$token = new UsernamePasswordToken('username', '', 'key', array('ROLE_FOO'));
$user = new User('username', 'password', array());
$this->tokenStorage->setToken($token);
$this->request->query->replace(array(
'_switch_user' => 'kuba',
'page' => 3,
'section' => 2,
));
$this->accessDecisionManager->expects($this->once())
->method('decide')->with($token, array('ROLE_ALLOWED_TO_SWITCH'))
->will($this->returnValue(true));
$this->userProvider->expects($this->once())
->method('loadUserByUsername')->with('kuba')
->will($this->returnValue($user));
$this->userChecker->expects($this->once())
->method('checkPostAuth')->with($user);
$listener = new SwitchUserListener($this->tokenStorage, $this->userProvider, $this->userChecker, 'provider123', $this->accessDecisionManager);
$listener->handle($this->event);
$this->assertSame('page=3&section=2', $this->request->server->get('QUERY_STRING'));
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken', $this->tokenStorage->getToken());
}
}

View File

@@ -0,0 +1,79 @@
<?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\Tests\Http\Firewall;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Firewall\UsernamePasswordFormAuthenticationListener;
use Symfony\Component\Security\Core\Security;
class UsernamePasswordFormAuthenticationListenerTest extends TestCase
{
/**
* @dataProvider getUsernameForLength
*/
public function testHandleWhenUsernameLength($username, $ok)
{
$request = Request::create('/login_check', 'POST', array('_username' => $username));
$request->setSession($this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils
->expects($this->any())
->method('checkRequestPath')
->will($this->returnValue(true))
;
$failureHandler = $this->getMockBuilder('Symfony\Component\Security\Http\Authentication\AuthenticationFailureHandlerInterface')->getMock();
$failureHandler
->expects($ok ? $this->never() : $this->once())
->method('onAuthenticationFailure')
->will($this->returnValue(new Response()))
;
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationProviderManager')->disableOriginalConstructor()->getMock();
$authenticationManager
->expects($ok ? $this->once() : $this->never())
->method('authenticate')
->will($this->returnValue(new Response()))
;
$listener = new UsernamePasswordFormAuthenticationListener(
$this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock(),
$authenticationManager,
$this->getMockBuilder('Symfony\Component\Security\Http\Session\SessionAuthenticationStrategyInterface')->getMock(),
$httpUtils,
'TheProviderKey',
$this->getMockBuilder('Symfony\Component\Security\Http\Authentication\AuthenticationSuccessHandlerInterface')->getMock(),
$failureHandler,
array('require_previous_session' => false)
);
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')->disableOriginalConstructor()->getMock();
$event
->expects($this->any())
->method('getRequest')
->will($this->returnValue($request))
;
$listener->handle($event);
}
public function getUsernameForLength()
{
return array(
array(str_repeat('x', Security::MAX_USERNAME_LENGTH + 1), false),
array(str_repeat('x', Security::MAX_USERNAME_LENGTH - 1), true),
);
}
}

View File

@@ -0,0 +1,124 @@
<?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\Security\Http\Firewall\X509AuthenticationListener;
class X509AuthenticationListenerTest extends TestCase
{
/**
* @dataProvider dataProviderGetPreAuthenticatedData
*/
public function testGetPreAuthenticatedData($user, $credentials)
{
$serverVars = array();
if ('' !== $user) {
$serverVars['SSL_CLIENT_S_DN_Email'] = $user;
}
if ('' !== $credentials) {
$serverVars['SSL_CLIENT_S_DN'] = $credentials;
}
$request = new Request(array(), array(), array(), array(), array(), $serverVars);
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey');
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, array($user, $credentials));
}
public static function dataProviderGetPreAuthenticatedData()
{
return array(
'validValues' => array('TheUser', 'TheCredentials'),
'noCredentials' => array('TheUser', ''),
);
}
/**
* @dataProvider dataProviderGetPreAuthenticatedDataNoUser
*/
public function testGetPreAuthenticatedDataNoUser($emailAddress)
{
$credentials = 'CN=Sample certificate DN/emailAddress='.$emailAddress;
$request = new Request(array(), array(), array(), array(), array(), array('SSL_CLIENT_S_DN' => $credentials));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey');
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, array($emailAddress, $credentials));
}
public static function dataProviderGetPreAuthenticatedDataNoUser()
{
return array(
'basicEmailAddress' => array('cert@example.com'),
'emailAddressWithPlusSign' => array('cert+something@example.com'),
);
}
/**
* @expectedException \Symfony\Component\Security\Core\Exception\BadCredentialsException
*/
public function testGetPreAuthenticatedDataNoData()
{
$request = new Request(array(), array(), array(), array(), array(), array());
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey');
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
}
public function testGetPreAuthenticatedDataWithDifferentKeys()
{
$userCredentials = array('TheUser', 'TheCredentials');
$request = new Request(array(), array(), array(), array(), array(), array(
'TheUserKey' => 'TheUser',
'TheCredentialsKey' => 'TheCredentials',
));
$tokenStorage = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface')->getMock();
$authenticationManager = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\AuthenticationManagerInterface')->getMock();
$listener = new X509AuthenticationListener($tokenStorage, $authenticationManager, 'TheProviderKey', 'TheUserKey', 'TheCredentialsKey');
$method = new \ReflectionMethod($listener, 'getPreAuthenticatedData');
$method->setAccessible(true);
$result = $method->invokeArgs($listener, array($request));
$this->assertSame($result, $userCredentials);
}
}

View File

@@ -0,0 +1,118 @@
<?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\Security\Http\FirewallMap;
use Symfony\Component\HttpFoundation\Request;
class FirewallMapTest extends TestCase
{
public function testGetListeners()
{
$map = new FirewallMap();
$request = new Request();
$notMatchingMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$notMatchingMatcher
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(false))
;
$map->add($notMatchingMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$matchingMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$matchingMatcher
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(true))
;
$theListener = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$theException = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ExceptionListener')->disableOriginalConstructor()->getMock();
$map->add($matchingMatcher, array($theListener), $theException);
$tooLateMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$tooLateMatcher
->expects($this->never())
->method('matches')
;
$map->add($tooLateMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
list($listeners, $exception) = $map->getListeners($request);
$this->assertEquals(array($theListener), $listeners);
$this->assertEquals($theException, $exception);
}
public function testGetListenersWithAnEntryHavingNoRequestMatcher()
{
$map = new FirewallMap();
$request = new Request();
$notMatchingMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$notMatchingMatcher
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(false))
;
$map->add($notMatchingMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
$theListener = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$theException = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ExceptionListener')->disableOriginalConstructor()->getMock();
$map->add(null, array($theListener), $theException);
$tooLateMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$tooLateMatcher
->expects($this->never())
->method('matches')
;
$map->add($tooLateMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
list($listeners, $exception) = $map->getListeners($request);
$this->assertEquals(array($theListener), $listeners);
$this->assertEquals($theException, $exception);
}
public function testGetListenersWithNoMatchingEntry()
{
$map = new FirewallMap();
$request = new Request();
$notMatchingMatcher = $this->getMockBuilder('Symfony\Component\HttpFoundation\RequestMatcher')->getMock();
$notMatchingMatcher
->expects($this->once())
->method('matches')
->with($this->equalTo($request))
->will($this->returnValue(false))
;
$map->add($notMatchingMatcher, array($this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock()));
list($listeners, $exception) = $map->getListeners($request);
$this->assertEquals(array(), $listeners);
$this->assertNull($exception);
}
}

View File

@@ -0,0 +1,110 @@
<?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\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\Firewall;
class FirewallTest extends TestCase
{
public function testOnKernelRequestRegistersExceptionListener()
{
$dispatcher = $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock();
$listener = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ExceptionListener')->disableOriginalConstructor()->getMock();
$listener
->expects($this->once())
->method('register')
->with($this->equalTo($dispatcher))
;
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock();
$map = $this->getMockBuilder('Symfony\Component\Security\Http\FirewallMapInterface')->getMock();
$map
->expects($this->once())
->method('getListeners')
->with($this->equalTo($request))
->will($this->returnValue(array(array(), $listener)))
;
$event = new GetResponseEvent($this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(), $request, HttpKernelInterface::MASTER_REQUEST);
$firewall = new Firewall($map, $dispatcher);
$firewall->onKernelRequest($event);
}
public function testOnKernelRequestStopsWhenThereIsAResponse()
{
$response = new Response();
$first = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$first
->expects($this->once())
->method('handle')
;
$second = $this->getMockBuilder('Symfony\Component\Security\Http\Firewall\ListenerInterface')->getMock();
$second
->expects($this->never())
->method('handle')
;
$map = $this->getMockBuilder('Symfony\Component\Security\Http\FirewallMapInterface')->getMock();
$map
->expects($this->once())
->method('getListeners')
->will($this->returnValue(array(array($first, $second), null)))
;
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\GetResponseEvent')
->setMethods(array('hasResponse'))
->setConstructorArgs(array(
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->disableOriginalConstructor()->disableOriginalClone()->getMock(),
HttpKernelInterface::MASTER_REQUEST,
))
->getMock()
;
$event
->expects($this->once())
->method('hasResponse')
->will($this->returnValue(true))
;
$firewall = new Firewall($map, $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock());
$firewall->onKernelRequest($event);
}
public function testOnKernelRequestWithSubRequest()
{
$map = $this->getMockBuilder('Symfony\Component\Security\Http\FirewallMapInterface')->getMock();
$map
->expects($this->never())
->method('getListeners')
;
$event = new GetResponseEvent(
$this->getMockBuilder('Symfony\Component\HttpKernel\HttpKernelInterface')->getMock(),
$this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock(),
HttpKernelInterface::SUB_REQUEST
);
$firewall = new Firewall($map, $this->getMockBuilder('Symfony\Component\EventDispatcher\EventDispatcherInterface')->getMock());
$firewall->onKernelRequest($event);
$this->assertFalse($event->hasResponse());
}
}

View File

@@ -0,0 +1,313 @@
<?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\Request;
use Symfony\Component\Routing\Exception\MethodNotAllowedException;
use Symfony\Component\Routing\Exception\ResourceNotFoundException;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Http\HttpUtils;
class HttpUtilsTest extends TestCase
{
public function testCreateRedirectResponseWithPath()
{
$utils = new HttpUtils($this->getUrlGenerator());
$response = $utils->createRedirectResponse($this->getRequest(), '/foobar');
$this->assertTrue($response->isRedirect('http://localhost/foobar'));
$this->assertEquals(302, $response->getStatusCode());
}
public function testCreateRedirectResponseWithAbsoluteUrl()
{
$utils = new HttpUtils($this->getUrlGenerator());
$response = $utils->createRedirectResponse($this->getRequest(), 'http://symfony.com/');
$this->assertTrue($response->isRedirect('http://symfony.com/'));
}
public function testCreateRedirectResponseWithDomainRegexp()
{
$utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://symfony\.com$#i');
$response = $utils->createRedirectResponse($this->getRequest(), 'http://symfony.com/blog');
$this->assertTrue($response->isRedirect('http://symfony.com/blog'));
}
public function testCreateRedirectResponseWithRequestsDomain()
{
$utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://%s$#i');
$response = $utils->createRedirectResponse($this->getRequest(), 'http://localhost/blog');
$this->assertTrue($response->isRedirect('http://localhost/blog'));
}
public function testCreateRedirectResponseWithBadRequestsDomain()
{
$utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://%s$#i');
$response = $utils->createRedirectResponse($this->getRequest(), 'http://pirate.net/foo');
$this->assertTrue($response->isRedirect('http://localhost/'));
}
public function testCreateRedirectResponseWithProtocolRelativeTarget()
{
$utils = new HttpUtils($this->getUrlGenerator(), null, '#^https?://%s$#i');
$response = $utils->createRedirectResponse($this->getRequest(), '//evil.com/do-bad-things');
$this->assertTrue($response->isRedirect('http://localhost//evil.com/do-bad-things'), 'Protocol-relative redirection should not be supported for security reasons');
}
public function testCreateRedirectResponseWithRouteName()
{
$utils = new HttpUtils($urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock());
$urlGenerator
->expects($this->any())
->method('generate')
->with('foobar', array(), UrlGeneratorInterface::ABSOLUTE_URL)
->will($this->returnValue('http://localhost/foo/bar'))
;
$urlGenerator
->expects($this->any())
->method('getContext')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock()))
;
$response = $utils->createRedirectResponse($this->getRequest(), 'foobar');
$this->assertTrue($response->isRedirect('http://localhost/foo/bar'));
}
public function testCreateRequestWithPath()
{
$request = $this->getRequest();
$request->server->set('Foo', 'bar');
$utils = new HttpUtils($this->getUrlGenerator());
$subRequest = $utils->createRequest($request, '/foobar');
$this->assertEquals('GET', $subRequest->getMethod());
$this->assertEquals('/foobar', $subRequest->getPathInfo());
$this->assertEquals('bar', $subRequest->server->get('Foo'));
}
public function testCreateRequestWithRouteName()
{
$utils = new HttpUtils($urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock());
$urlGenerator
->expects($this->once())
->method('generate')
->will($this->returnValue('/foo/bar'))
;
$urlGenerator
->expects($this->any())
->method('getContext')
->will($this->returnValue($this->getMockBuilder('Symfony\Component\Routing\RequestContext')->getMock()))
;
$subRequest = $utils->createRequest($this->getRequest(), 'foobar');
$this->assertEquals('/foo/bar', $subRequest->getPathInfo());
}
public function testCreateRequestWithAbsoluteUrl()
{
$utils = new HttpUtils($this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock());
$subRequest = $utils->createRequest($this->getRequest(), 'http://symfony.com/');
$this->assertEquals('/', $subRequest->getPathInfo());
}
public function testCreateRequestPassesSessionToTheNewRequest()
{
$request = $this->getRequest();
$request->setSession($session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock());
$utils = new HttpUtils($this->getUrlGenerator());
$subRequest = $utils->createRequest($request, '/foobar');
$this->assertSame($session, $subRequest->getSession());
}
/**
* @dataProvider provideSecurityContextAttributes
*/
public function testCreateRequestPassesSecurityContextAttributesToTheNewRequest($attribute)
{
$request = $this->getRequest();
$request->attributes->set($attribute, 'foo');
$utils = new HttpUtils($this->getUrlGenerator());
$subRequest = $utils->createRequest($request, '/foobar');
$this->assertSame('foo', $subRequest->attributes->get($attribute));
}
public function provideSecurityContextAttributes()
{
return array(
array(Security::AUTHENTICATION_ERROR),
array(Security::ACCESS_DENIED_ERROR),
array(Security::LAST_USERNAME),
);
}
public function testCheckRequestPath()
{
$utils = new HttpUtils($this->getUrlGenerator());
$this->assertTrue($utils->checkRequestPath($this->getRequest(), '/'));
$this->assertFalse($utils->checkRequestPath($this->getRequest(), '/foo'));
$this->assertTrue($utils->checkRequestPath($this->getRequest('/foo%20bar'), '/foo bar'));
// Plus must not decoded to space
$this->assertTrue($utils->checkRequestPath($this->getRequest('/foo+bar'), '/foo+bar'));
// Checking unicode
$this->assertTrue($utils->checkRequestPath($this->getRequest('/'.urlencode('вход')), '/вход'));
}
public function testCheckRequestPathWithUrlMatcherAndResourceNotFound()
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('match')
->with('/')
->will($this->throwException(new ResourceNotFoundException()))
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertFalse($utils->checkRequestPath($this->getRequest(), 'foobar'));
}
public function testCheckRequestPathWithUrlMatcherAndMethodNotAllowed()
{
$request = $this->getRequest();
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('matchRequest')
->with($request)
->will($this->throwException(new MethodNotAllowedException(array())))
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertFalse($utils->checkRequestPath($request, 'foobar'));
}
public function testCheckRequestPathWithUrlMatcherAndResourceFoundByUrl()
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('match')
->with('/foo/bar')
->will($this->returnValue(array('_route' => 'foobar')))
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertTrue($utils->checkRequestPath($this->getRequest('/foo/bar'), 'foobar'));
}
public function testCheckRequestPathWithUrlMatcherAndResourceFoundByRequest()
{
$request = $this->getRequest();
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\RequestMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('matchRequest')
->with($request)
->will($this->returnValue(array('_route' => 'foobar')))
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertTrue($utils->checkRequestPath($request, 'foobar'));
}
/**
* @expectedException \RuntimeException
*/
public function testCheckRequestPathWithUrlMatcherLoadingException()
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('match')
->will($this->throwException(new \RuntimeException()))
;
$utils = new HttpUtils(null, $urlMatcher);
$utils->checkRequestPath($this->getRequest(), 'foobar');
}
public function testCheckPathWithoutRouteParam()
{
$urlMatcher = $this->getMockBuilder('Symfony\Component\Routing\Matcher\UrlMatcherInterface')->getMock();
$urlMatcher
->expects($this->any())
->method('match')
->willReturn(array('_controller' => 'PathController'))
;
$utils = new HttpUtils(null, $urlMatcher);
$this->assertFalse($utils->checkRequestPath($this->getRequest(), 'path/index.html'));
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage Matcher must either implement UrlMatcherInterface or RequestMatcherInterface
*/
public function testUrlMatcher()
{
new HttpUtils($this->getUrlGenerator(), new \stdClass());
}
public function testGenerateUriRemovesQueryString()
{
$utils = new HttpUtils($this->getUrlGenerator('/foo/bar'));
$this->assertEquals('/foo/bar', $utils->generateUri(new Request(), 'route_name'));
$utils = new HttpUtils($this->getUrlGenerator('/foo/bar?param=value'));
$this->assertEquals('/foo/bar', $utils->generateUri(new Request(), 'route_name'));
}
/**
* @expectedException \LogicException
* @expectedExceptionMessage You must provide a UrlGeneratorInterface instance to be able to use routes.
*/
public function testUrlGeneratorIsRequiredToGenerateUrl()
{
$utils = new HttpUtils();
$utils->generateUri(new Request(), 'route_name');
}
private function getUrlGenerator($generatedUrl = '/foo/bar')
{
$urlGenerator = $this->getMockBuilder('Symfony\Component\Routing\Generator\UrlGeneratorInterface')->getMock();
$urlGenerator
->expects($this->any())
->method('generate')
->will($this->returnValue($generatedUrl))
;
return $urlGenerator;
}
private function getRequest($path = '/')
{
return Request::create($path, 'get');
}
}

View File

@@ -0,0 +1,50 @@
<?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\Logout;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Logout\CookieClearingLogoutHandler;
class CookieClearingLogoutHandlerTest extends TestCase
{
public function testLogout()
{
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$handler = new CookieClearingLogoutHandler(array('foo' => array('path' => '/foo', 'domain' => 'foo.foo'), 'foo2' => array('path' => null, 'domain' => null)));
$cookies = $response->headers->getCookies();
$this->assertCount(0, $cookies);
$handler->logout($request, $response, $token);
$cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$this->assertCount(2, $cookies);
$cookie = $cookies['foo.foo']['/foo']['foo'];
$this->assertEquals('foo', $cookie->getName());
$this->assertEquals('/foo', $cookie->getPath());
$this->assertEquals('foo.foo', $cookie->getDomain());
$this->assertTrue($cookie->isCleared());
$cookie = $cookies['']['/']['foo2'];
$this->assertStringStartsWith('foo2', $cookie->getName());
$this->assertEquals('/', $cookie->getPath());
$this->assertNull($cookie->getDomain());
$this->assertTrue($cookie->isCleared());
}
}

View File

@@ -0,0 +1,36 @@
<?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\Logout;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\DefaultLogoutSuccessHandler;
class DefaultLogoutSuccessHandlerTest extends TestCase
{
public function testLogout()
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$response = new Response();
$httpUtils = $this->getMockBuilder('Symfony\Component\Security\Http\HttpUtils')->getMock();
$httpUtils->expects($this->once())
->method('createRedirectResponse')
->with($request, '/dashboard')
->will($this->returnValue($response));
$handler = new DefaultLogoutSuccessHandler($httpUtils, '/dashboard');
$result = $handler->onLogoutSuccess($request);
$this->assertSame($response, $result);
}
}

View File

@@ -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\Component\Security\Http\Tests\Logout;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\Logout\SessionLogoutHandler;
class SessionLogoutHandlerTest extends TestCase
{
public function testLogout()
{
$handler = new SessionLogoutHandler();
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
$response = new Response();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\Session')->disableOriginalConstructor()->getMock();
$request
->expects($this->once())
->method('getSession')
->will($this->returnValue($session))
;
$session
->expects($this->once())
->method('invalidate')
;
$handler->logout($request, $response, $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock());
}
}

View File

@@ -0,0 +1,313 @@
<?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\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices;
class AbstractRememberMeServicesTest extends TestCase
{
public function testGetRememberMeParameter()
{
$service = $this->getService(null, array('remember_me_parameter' => 'foo'));
$this->assertEquals('foo', $service->getRememberMeParameter());
}
public function testGetSecret()
{
$service = $this->getService();
$this->assertEquals('foosecret', $service->getSecret());
}
public function testAutoLoginReturnsNullWhenNoCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$this->assertNull($service->autoLogin(new Request()));
}
/**
* @expectedException \RuntimeException
*/
public function testAutoLoginThrowsExceptionWhenImplementationDoesNotReturnUserInterface()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$request->cookies->set('foo', 'foo');
$service
->expects($this->once())
->method('processAutoLoginCookie')
->will($this->returnValue(null))
;
$service->autoLogin($request);
}
public function testAutoLogin()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$request->cookies->set('foo', 'foo');
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array()))
;
$service
->expects($this->once())
->method('processAutoLoginCookie')
->will($this->returnValue($user))
;
$returnedToken = $service->autoLogin($request);
$this->assertSame($user, $returnedToken->getUser());
$this->assertSame('foosecret', $returnedToken->getSecret());
$this->assertSame('fookey', $returnedToken->getProviderKey());
}
/**
* @dataProvider provideOptionsForLogout
*/
public function testLogout(array $options)
{
$service = $this->getService(null, $options);
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service->logout($request, $response, $token);
$cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
$this->assertInstanceOf('Symfony\Component\HttpFoundation\Cookie', $cookie);
$this->assertTrue($cookie->isCleared());
$this->assertSame($options['name'], $cookie->getName());
$this->assertSame($options['path'], $cookie->getPath());
$this->assertSame($options['domain'], $cookie->getDomain());
$this->assertSame($options['secure'], $cookie->isSecure());
$this->assertSame($options['httponly'], $cookie->isHttpOnly());
}
public function provideOptionsForLogout()
{
return array(
array(array('name' => 'foo', 'path' => '/', 'domain' => null, 'secure' => false, 'httponly' => true)),
array(array('name' => 'foo', 'path' => '/bar', 'domain' => 'baz.com', 'secure' => true, 'httponly' => false)),
);
}
public function testLoginFail()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$service->loginFail($request);
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testLoginSuccessIsNotProcessedWhenTokenDoesNotContainUserInterfaceImplementation()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue('foo'))
;
$service
->expects($this->never())
->method('onLoginSuccess')
;
$this->assertFalse($request->request->has('foo'));
$service->loginSuccess($request, $response, $token);
}
public function testLoginSuccessIsNotProcessedWhenRememberMeIsNotRequested()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
;
$service
->expects($this->never())
->method('onLoginSuccess')
->will($this->returnValue(null))
;
$this->assertFalse($request->request->has('foo'));
$service->loginSuccess($request, $response, $token);
}
public function testLoginSuccessWhenRememberMeAlwaysIsTrue()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
;
$service
->expects($this->once())
->method('onLoginSuccess')
->will($this->returnValue(null))
;
$service->loginSuccess($request, $response, $token);
}
/**
* @dataProvider getPositiveRememberMeParameterValues
*/
public function testLoginSuccessWhenRememberMeParameterWithPathIsPositive($value)
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo[bar]', 'path' => null, 'domain' => null));
$request = new Request();
$request->request->set('foo', array('bar' => $value));
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
;
$service
->expects($this->once())
->method('onLoginSuccess')
->will($this->returnValue(true))
;
$service->loginSuccess($request, $response, $token);
}
/**
* @dataProvider getPositiveRememberMeParameterValues
*/
public function testLoginSuccessWhenRememberMeParameterIsPositive($value)
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => false, 'remember_me_parameter' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$request->request->set('foo', $value);
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue($account))
;
$service
->expects($this->once())
->method('onLoginSuccess')
->will($this->returnValue(true))
;
$service->loginSuccess($request, $response, $token);
}
public function getPositiveRememberMeParameterValues()
{
return array(
array('true'),
array('1'),
array('on'),
array('yes'),
array(true),
);
}
public function testEncodeCookieAndDecodeCookieAreInvertible()
{
$cookieParts = array('aa', 'bb', 'cc');
$service = $this->getService();
$encoded = $this->callProtected($service, 'encodeCookie', array($cookieParts));
$this->assertInternalType('string', $encoded);
$decoded = $this->callProtected($service, 'decodeCookie', array($encoded));
$this->assertSame($cookieParts, $decoded);
}
/**
* @expectedException \InvalidArgumentException
* @expectedExceptionMessage cookie delimiter
*/
public function testThereShouldBeNoCookieDelimiterInCookieParts()
{
$cookieParts = array('aa', 'b'.AbstractRememberMeServices::COOKIE_DELIMITER.'b', 'cc');
$service = $this->getService();
$this->callProtected($service, 'encodeCookie', array($cookieParts));
}
protected function getService($userProvider = null, $options = array(), $logger = null)
{
if (null === $userProvider) {
$userProvider = $this->getProvider();
}
return $this->getMockForAbstractClass('Symfony\Component\Security\Http\RememberMe\AbstractRememberMeServices', array(
array($userProvider), 'foosecret', 'fookey', $options, $logger,
));
}
protected function getProvider()
{
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$provider
->expects($this->any())
->method('supportsClass')
->will($this->returnValue(true))
;
return $provider;
}
private function callProtected($object, $method, array $args)
{
$reflection = new \ReflectionClass(get_class($object));
$reflectionMethod = $reflection->getMethod($method);
$reflectionMethod->setAccessible(true);
return $reflectionMethod->invokeArgs($object, $args);
}
}

View File

@@ -0,0 +1,339 @@
<?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\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\Security\Core\Authentication\RememberMe\PersistentToken;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Http\RememberMe\PersistentTokenBasedRememberMeServices;
use Symfony\Component\Security\Core\Exception\TokenNotFoundException;
use Symfony\Component\Security\Core\Exception\CookieTheftException;
class PersistentTokenBasedRememberMeServicesTest extends TestCase
{
public static function setUpBeforeClass()
{
try {
random_bytes(1);
} catch (\Exception $e) {
self::markTestSkipped($e->getMessage());
}
}
public function testAutoLoginReturnsNullWhenNoCookie()
{
$service = $this->getService(null, array('name' => 'foo'));
$this->assertNull($service->autoLogin(new Request()));
}
public function testAutoLoginThrowsExceptionOnInvalidCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
$request = new Request();
$request->request->set('foo', 'true');
$request->cookies->set('foo', 'foo');
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testAutoLoginThrowsExceptionOnNonExistentToken()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
$request = new Request();
$request->request->set('foo', 'true');
$request->cookies->set('foo', $this->encodeCookie(array(
$series = 'fooseries',
$tokenValue = 'foovalue',
)));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->will($this->throwException(new TokenNotFoundException('Token not found.')))
;
$service->setTokenProvider($tokenProvider);
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testAutoLoginReturnsNullOnNonExistentUser()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600, 'secure' => false, 'httponly' => false));
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->will($this->returnValue(new PersistentToken('fooclass', 'fooname', 'fooseries', 'foovalue', new \DateTime())))
;
$service->setTokenProvider($tokenProvider);
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException('user not found')))
;
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
}
public function testAutoLoginThrowsExceptionOnStolenCookieAndRemovesItFromThePersistentBackend()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true));
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$service->setTokenProvider($tokenProvider);
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'anotherFooValue', new \DateTime())))
;
$tokenProvider
->expects($this->once())
->method('deleteTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(null))
;
try {
$service->autoLogin($request);
$this->fail('Expected CookieTheftException was not thrown.');
} catch (CookieTheftException $e) {
}
$this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
}
public function testAutoLoginDoesNotAcceptAnExpiredCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(new PersistentToken('fooclass', 'username', 'fooseries', 'foovalue', new \DateTime('yesterday'))))
;
$service->setTokenProvider($tokenProvider);
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
}
public function testAutoLogin()
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
;
$userProvider = $this->getProvider();
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foouser'))
->will($this->returnValue($user))
;
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => false, 'httponly' => false, 'always_remember_me' => true, 'lifetime' => 3600));
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('loadTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(new PersistentToken('fooclass', 'foouser', 'fooseries', 'foovalue', new \DateTime())))
;
$service->setTokenProvider($tokenProvider);
$returnedToken = $service->autoLogin($request);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $returnedToken);
$this->assertSame($user, $returnedToken->getUser());
$this->assertEquals('foosecret', $returnedToken->getSecret());
$this->assertTrue($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
}
public function testLogout()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo', 'secure' => true, 'httponly' => false));
$request = new Request();
$request->cookies->set('foo', $this->encodeCookie(array('fooseries', 'foovalue')));
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('deleteTokenBySeries')
->with($this->equalTo('fooseries'))
->will($this->returnValue(null))
;
$service->setTokenProvider($tokenProvider);
$service->logout($request, $response, $token);
$cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
$this->assertTrue($cookie->isCleared());
$this->assertEquals('/foo', $cookie->getPath());
$this->assertEquals('foodomain.foo', $cookie->getDomain());
$this->assertTrue($cookie->isSecure());
$this->assertFalse($cookie->isHttpOnly());
}
public function testLogoutSimplyIgnoresNonSetRequestCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->never())
->method('deleteTokenBySeries')
;
$service->setTokenProvider($tokenProvider);
$service->logout($request, $response, $token);
$cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
$this->assertTrue($cookie->isCleared());
$this->assertEquals('/', $cookie->getPath());
$this->assertNull($cookie->getDomain());
}
public function testLogoutSimplyIgnoresInvalidCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$request->cookies->set('foo', 'somefoovalue');
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->never())
->method('deleteTokenBySeries')
;
$service->setTokenProvider($tokenProvider);
$service->logout($request, $response, $token);
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testLoginFail()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null));
$request = new Request();
$this->assertFalse($request->attributes->has(RememberMeServicesInterface::COOKIE_ATTR_NAME));
$service->loginFail($request);
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testLoginSuccessSetsCookieWhenLoggedInWithNonRememberMeTokenInterfaceImplementation()
{
$service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
$request = new Request();
$response = new Response();
$account = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$account
->expects($this->once())
->method('getUsername')
->will($this->returnValue('foo'))
;
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->any())
->method('getUser')
->will($this->returnValue($account))
;
$tokenProvider = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\RememberMe\TokenProviderInterface')->getMock();
$tokenProvider
->expects($this->once())
->method('createNewToken')
;
$service->setTokenProvider($tokenProvider);
$cookies = $response->headers->getCookies();
$this->assertCount(0, $cookies);
$service->loginSuccess($request, $response, $token);
$cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$cookie = $cookies['myfoodomain.foo']['/foo/path']['foo'];
$this->assertFalse($cookie->isCleared());
$this->assertTrue($cookie->isSecure());
$this->assertTrue($cookie->isHttpOnly());
$this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
$this->assertEquals('myfoodomain.foo', $cookie->getDomain());
$this->assertEquals('/foo/path', $cookie->getPath());
}
protected function encodeCookie(array $parts)
{
$service = $this->getService();
$r = new \ReflectionMethod($service, 'encodeCookie');
$r->setAccessible(true);
return $r->invoke($service, $parts);
}
protected function getService($userProvider = null, $options = array(), $logger = null)
{
if (null === $userProvider) {
$userProvider = $this->getProvider();
}
return new PersistentTokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger);
}
protected function getProvider()
{
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$provider
->expects($this->any())
->method('supportsClass')
->will($this->returnValue(true))
;
return $provider;
}
}

View File

@@ -0,0 +1,104 @@
<?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\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Http\RememberMe\ResponseListener;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpKernel\KernelEvents;
class ResponseListenerTest extends TestCase
{
public function testRememberMeCookieIsSentWithResponse()
{
$cookie = new Cookie('rememberme');
$request = $this->getRequest(array(
RememberMeServicesInterface::COOKIE_ATTR_NAME => $cookie,
));
$response = $this->getResponse();
$response->headers->expects($this->once())->method('setCookie')->with($cookie);
$listener = new ResponseListener();
$listener->onKernelResponse($this->getEvent($request, $response));
}
public function testRememberMeCookieIsNotSendWithResponseForSubRequests()
{
$cookie = new Cookie('rememberme');
$request = $this->getRequest(array(
RememberMeServicesInterface::COOKIE_ATTR_NAME => $cookie,
));
$response = $this->getResponse();
$response->headers->expects($this->never())->method('setCookie');
$listener = new ResponseListener();
$listener->onKernelResponse($this->getEvent($request, $response, HttpKernelInterface::SUB_REQUEST));
}
public function testRememberMeCookieIsNotSendWithResponse()
{
$request = $this->getRequest();
$response = $this->getResponse();
$response->headers->expects($this->never())->method('setCookie');
$listener = new ResponseListener();
$listener->onKernelResponse($this->getEvent($request, $response));
}
public function testItSubscribesToTheOnKernelResponseEvent()
{
$listener = new ResponseListener();
$this->assertSame(array(KernelEvents::RESPONSE => 'onKernelResponse'), ResponseListener::getSubscribedEvents());
}
private function getRequest(array $attributes = array())
{
$request = new Request();
foreach ($attributes as $name => $value) {
$request->attributes->set($name, $value);
}
return $request;
}
private function getResponse()
{
$response = new Response();
$response->headers = $this->getMockBuilder('Symfony\Component\HttpFoundation\ResponseHeaderBag')->getMock();
return $response;
}
private function getEvent($request, $response, $type = HttpKernelInterface::MASTER_REQUEST)
{
$event = $this->getMockBuilder('Symfony\Component\HttpKernel\Event\FilterResponseEvent')
->disableOriginalConstructor()
->getMock();
$event->expects($this->any())->method('getRequest')->will($this->returnValue($request));
$event->expects($this->any())->method('isMasterRequest')->will($this->returnValue($type === HttpKernelInterface::MASTER_REQUEST));
$event->expects($this->any())->method('getResponse')->will($this->returnValue($response));
return $event;
}
}

View File

@@ -0,0 +1,285 @@
<?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\RememberMe;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\RememberMe\RememberMeServicesInterface;
use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\ResponseHeaderBag;
use Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices;
class TokenBasedRememberMeServicesTest extends TestCase
{
public function testAutoLoginReturnsNullWhenNoCookie()
{
$service = $this->getService(null, array('name' => 'foo'));
$this->assertNull($service->autoLogin(new Request()));
}
public function testAutoLoginThrowsExceptionOnInvalidCookie()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => false, 'remember_me_parameter' => 'foo'));
$request = new Request();
$request->request->set('foo', 'true');
$request->cookies->set('foo', 'foo');
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testAutoLoginThrowsExceptionOnNonExistentUser()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$request = new Request();
$request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() + 3600, 'foopass'));
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->will($this->throwException(new UsernameNotFoundException('user not found')))
;
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testAutoLoginDoesNotAcceptCookieWithInvalidHash()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$request = new Request();
$request->cookies->set('foo', base64_encode('class:'.base64_encode('foouser').':123456789:fooHash'));
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
;
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foouser'))
->will($this->returnValue($user))
;
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
public function testAutoLoginDoesNotAcceptAnExpiredCookie()
{
$userProvider = $this->getProvider();
$service = $this->getService($userProvider, array('name' => 'foo', 'path' => null, 'domain' => null, 'always_remember_me' => true, 'lifetime' => 3600));
$request = new Request();
$request->cookies->set('foo', $this->getCookie('fooclass', 'foouser', time() - 1, 'foopass'));
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
;
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo('foouser'))
->will($this->returnValue($user))
;
$this->assertNull($service->autoLogin($request));
$this->assertTrue($request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME)->isCleared());
}
/**
* @dataProvider provideUsernamesForAutoLogin
*
* @param string $username
*/
public function testAutoLogin($username)
{
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getRoles')
->will($this->returnValue(array('ROLE_FOO')))
;
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
;
$userProvider = $this->getProvider();
$userProvider
->expects($this->once())
->method('loadUserByUsername')
->with($this->equalTo($username))
->will($this->returnValue($user))
;
$service = $this->getService($userProvider, array('name' => 'foo', 'always_remember_me' => true, 'lifetime' => 3600));
$request = new Request();
$request->cookies->set('foo', $this->getCookie('fooclass', $username, time() + 3600, 'foopass'));
$returnedToken = $service->autoLogin($request);
$this->assertInstanceOf('Symfony\Component\Security\Core\Authentication\Token\RememberMeToken', $returnedToken);
$this->assertSame($user, $returnedToken->getUser());
$this->assertEquals('foosecret', $returnedToken->getSecret());
}
public function provideUsernamesForAutoLogin()
{
return array(
array('foouser', 'Simple username'),
array('foo'.TokenBasedRememberMeServices::COOKIE_DELIMITER.'user', 'Username might contain the delimiter'),
);
}
public function testLogout()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => null, 'domain' => null, 'secure' => true, 'httponly' => false));
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$service->logout($request, $response, $token);
$cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
$this->assertTrue($cookie->isCleared());
$this->assertEquals('/', $cookie->getPath());
$this->assertNull($cookie->getDomain());
$this->assertTrue($cookie->isSecure());
$this->assertFalse($cookie->isHttpOnly());
}
public function testLoginFail()
{
$service = $this->getService(null, array('name' => 'foo', 'path' => '/foo', 'domain' => 'foodomain.foo'));
$request = new Request();
$service->loginFail($request);
$cookie = $request->attributes->get(RememberMeServicesInterface::COOKIE_ATTR_NAME);
$this->assertTrue($cookie->isCleared());
$this->assertEquals('/foo', $cookie->getPath());
$this->assertEquals('foodomain.foo', $cookie->getDomain());
}
public function testLoginSuccessIgnoresTokensWhichDoNotContainAnUserInterfaceImplementation()
{
$service = $this->getService(null, array('name' => 'foo', 'always_remember_me' => true, 'path' => null, 'domain' => null));
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$token
->expects($this->once())
->method('getUser')
->will($this->returnValue('foo'))
;
$cookies = $response->headers->getCookies();
$this->assertCount(0, $cookies);
$service->loginSuccess($request, $response, $token);
$cookies = $response->headers->getCookies();
$this->assertCount(0, $cookies);
}
public function testLoginSuccess()
{
$service = $this->getService(null, array('name' => 'foo', 'domain' => 'myfoodomain.foo', 'path' => '/foo/path', 'secure' => true, 'httponly' => true, 'lifetime' => 3600, 'always_remember_me' => true));
$request = new Request();
$response = new Response();
$token = $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
$user = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserInterface')->getMock();
$user
->expects($this->once())
->method('getPassword')
->will($this->returnValue('foopass'))
;
$user
->expects($this->once())
->method('getUsername')
->will($this->returnValue('foouser'))
;
$token
->expects($this->atLeastOnce())
->method('getUser')
->will($this->returnValue($user))
;
$cookies = $response->headers->getCookies();
$this->assertCount(0, $cookies);
$service->loginSuccess($request, $response, $token);
$cookies = $response->headers->getCookies(ResponseHeaderBag::COOKIES_ARRAY);
$cookie = $cookies['myfoodomain.foo']['/foo/path']['foo'];
$this->assertFalse($cookie->isCleared());
$this->assertTrue($cookie->isSecure());
$this->assertTrue($cookie->isHttpOnly());
$this->assertTrue($cookie->getExpiresTime() > time() + 3590 && $cookie->getExpiresTime() < time() + 3610);
$this->assertEquals('myfoodomain.foo', $cookie->getDomain());
$this->assertEquals('/foo/path', $cookie->getPath());
}
protected function getCookie($class, $username, $expires, $password)
{
$service = $this->getService();
$r = new \ReflectionMethod($service, 'generateCookieValue');
$r->setAccessible(true);
return $r->invoke($service, $class, $username, $expires, $password);
}
protected function encodeCookie(array $parts)
{
$service = $this->getService();
$r = new \ReflectionMethod($service, 'encodeCookie');
$r->setAccessible(true);
return $r->invoke($service, $parts);
}
protected function getService($userProvider = null, $options = array(), $logger = null)
{
if (null === $userProvider) {
$userProvider = $this->getProvider();
}
$service = new TokenBasedRememberMeServices(array($userProvider), 'foosecret', 'fookey', $options, $logger);
return $service;
}
protected function getProvider()
{
$provider = $this->getMockBuilder('Symfony\Component\Security\Core\User\UserProviderInterface')->getMock();
$provider
->expects($this->any())
->method('supportsClass')
->will($this->returnValue(true))
;
return $provider;
}
}

View File

@@ -0,0 +1,74 @@
<?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\Session;
use PHPUnit\Framework\TestCase;
use Symfony\Component\Security\Http\Session\SessionAuthenticationStrategy;
class SessionAuthenticationStrategyTest extends TestCase
{
public function testSessionIsNotChanged()
{
$request = $this->getRequest();
$request->expects($this->never())->method('getSession');
$strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::NONE);
$strategy->onAuthentication($request, $this->getToken());
}
/**
* @expectedException \RuntimeException
* @expectedExceptionMessage Invalid session authentication strategy "foo"
*/
public function testUnsupportedStrategy()
{
$request = $this->getRequest();
$request->expects($this->never())->method('getSession');
$strategy = new SessionAuthenticationStrategy('foo');
$strategy->onAuthentication($request, $this->getToken());
}
public function testSessionIsMigrated()
{
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session->expects($this->once())->method('migrate')->with($this->equalTo(true));
$strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::MIGRATE);
$strategy->onAuthentication($this->getRequest($session), $this->getToken());
}
public function testSessionIsInvalidated()
{
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')->getMock();
$session->expects($this->once())->method('invalidate');
$strategy = new SessionAuthenticationStrategy(SessionAuthenticationStrategy::INVALIDATE);
$strategy->onAuthentication($this->getRequest($session), $this->getToken());
}
private function getRequest($session = null)
{
$request = $this->getMockBuilder('Symfony\Component\HttpFoundation\Request')->getMock();
if (null !== $session) {
$request->expects($this->any())->method('getSession')->will($this->returnValue($session));
}
return $request;
}
private function getToken()
{
return $this->getMockBuilder('Symfony\Component\Security\Core\Authentication\Token\TokenInterface')->getMock();
}
}

View File

@@ -0,0 +1,77 @@
<?php
namespace Symfony\Component\Security\Http\Tests\Util;
use PHPUnit\Framework\TestCase;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
class TargetPathTraitTest extends TestCase
{
public function testSetTargetPath()
{
$obj = new TestClassWithTargetPathTrait();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')
->getMock();
$session->expects($this->once())
->method('set')
->with('_security.firewall_name.target_path', '/foo');
$obj->doSetTargetPath($session, 'firewall_name', '/foo');
}
public function testGetTargetPath()
{
$obj = new TestClassWithTargetPathTrait();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')
->getMock();
$session->expects($this->once())
->method('get')
->with('_security.cool_firewall.target_path')
->willReturn('/bar');
$actualUri = $obj->doGetTargetPath($session, 'cool_firewall');
$this->assertEquals(
'/bar',
$actualUri
);
}
public function testRemoveTargetPath()
{
$obj = new TestClassWithTargetPathTrait();
$session = $this->getMockBuilder('Symfony\Component\HttpFoundation\Session\SessionInterface')
->getMock();
$session->expects($this->once())
->method('remove')
->with('_security.best_firewall.target_path');
$obj->doRemoveTargetPath($session, 'best_firewall');
}
}
class TestClassWithTargetPathTrait
{
use TargetPathTrait;
public function doSetTargetPath(SessionInterface $session, $providerKey, $uri)
{
$this->saveTargetPath($session, $providerKey, $uri);
}
public function doGetTargetPath(SessionInterface $session, $providerKey)
{
return $this->getTargetPath($session, $providerKey);
}
public function doRemoveTargetPath(SessionInterface $session, $providerKey)
{
$this->removeTargetPath($session, $providerKey);
}
}

View File

@@ -0,0 +1,58 @@
<?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\Util;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
/**
* Trait to get (and set) the URL the user last visited before being forced to authenticate.
*/
trait TargetPathTrait
{
/**
* Sets the target path the user should be redirected to after authentication.
*
* Usually, you do not need to set this directly.
*
* @param SessionInterface $session
* @param string $providerKey The name of your firewall
* @param string $uri The URI to set as the target path
*/
private function saveTargetPath(SessionInterface $session, $providerKey, $uri)
{
$session->set('_security.'.$providerKey.'.target_path', $uri);
}
/**
* Returns the URL (if any) the user visited that forced them to login.
*
* @param SessionInterface $session
* @param string $providerKey The name of your firewall
*
* @return string
*/
private function getTargetPath(SessionInterface $session, $providerKey)
{
return $session->get('_security.'.$providerKey.'.target_path');
}
/**
* Removes the target path from the session.
*
* @param SessionInterface $session
* @param string $providerKey The name of your firewall
*/
private function removeTargetPath(SessionInterface $session, $providerKey)
{
$session->remove('_security.'.$providerKey.'.target_path');
}
}

View File

@@ -0,0 +1,49 @@
{
"name": "symfony/security-http",
"type": "library",
"description": "Symfony Security Component - HTTP Integration",
"keywords": [],
"homepage": "https://symfony.com",
"license": "MIT",
"authors": [
{
"name": "Fabien Potencier",
"email": "fabien@symfony.com"
},
{
"name": "Symfony Community",
"homepage": "https://symfony.com/contributors"
}
],
"require": {
"php": ">=5.5.9",
"symfony/security-core": "~3.2",
"symfony/event-dispatcher": "~2.8|~3.0",
"symfony/http-foundation": "~2.8|~3.0",
"symfony/http-kernel": "~2.8|~3.0",
"symfony/polyfill-php56": "~1.0",
"symfony/polyfill-php70": "~1.0",
"symfony/property-access": "~2.8|~3.0"
},
"require-dev": {
"symfony/routing": "~2.8|~3.0",
"symfony/security-csrf": "~2.8|~3.0",
"psr/log": "~1.0"
},
"suggest": {
"symfony/security-csrf": "For using tokens to protect authentication/logout attempts",
"symfony/routing": "For using the HttpUtils class to create sub-requests, redirect the user, and match URLs"
},
"autoload": {
"psr-4": { "Symfony\\Component\\Security\\Http\\": "" },
"exclude-from-classmap": [
"/Tests/"
]
},
"minimum-stability": "dev",
"extra": {
"branch-alias": {
"dev-master": "3.2-dev"
}
}
}

View File

@@ -0,0 +1,30 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://schema.phpunit.de/4.1/phpunit.xsd"
backupGlobals="false"
colors="true"
bootstrap="vendor/autoload.php"
failOnRisky="true"
failOnWarning="true"
>
<php>
<ini name="error_reporting" value="-1" />
</php>
<testsuites>
<testsuite name="Symfony Security Component HTTP Test Suite">
<directory>./Tests/</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory>./</directory>
<exclude>
<directory>./Tests</directory>
<directory>./vendor</directory>
</exclude>
</whitelist>
</filter>
</phpunit>