Actualización

This commit is contained in:
Xes
2025-04-10 12:24:57 +02:00
parent 8969cc929d
commit 45420b6f0d
39760 changed files with 4303286 additions and 0 deletions

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());
}
}