AbstractRememberMeServices.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. /*
  3. * This file is part of the Symfony package.
  4. *
  5. * (c) Fabien Potencier <fabien@symfony.com>
  6. *
  7. * For the full copyright and license information, please view the LICENSE
  8. * file that was distributed with this source code.
  9. */
  10. namespace Symfony\Component\Security\Http\RememberMe;
  11. use Psr\Log\LoggerInterface;
  12. use Symfony\Component\HttpFoundation\Cookie;
  13. use Symfony\Component\HttpFoundation\Request;
  14. use Symfony\Component\HttpFoundation\Response;
  15. use Symfony\Component\Security\Core\Authentication\Token\RememberMeToken;
  16. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  17. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  18. use Symfony\Component\Security\Core\Exception\CookieTheftException;
  19. use Symfony\Component\Security\Core\Exception\UnsupportedUserException;
  20. use Symfony\Component\Security\Core\Exception\UsernameNotFoundException;
  21. use Symfony\Component\Security\Core\User\UserInterface;
  22. use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface;
  23. use Symfony\Component\Security\Http\ParameterBagUtils;
  24. /**
  25. * Base class implementing the RememberMeServicesInterface.
  26. *
  27. * @author Johannes M. Schmitt <schmittjoh@gmail.com>
  28. */
  29. abstract class AbstractRememberMeServices implements RememberMeServicesInterface, LogoutHandlerInterface
  30. {
  31. const COOKIE_DELIMITER = ':';
  32. protected $logger;
  33. protected $options = array(
  34. 'secure' => false,
  35. 'httponly' => true,
  36. );
  37. private $providerKey;
  38. private $secret;
  39. private $userProviders;
  40. /**
  41. * @param array $userProviders
  42. * @param string $secret
  43. * @param string $providerKey
  44. * @param array $options
  45. * @param LoggerInterface $logger
  46. *
  47. * @throws \InvalidArgumentException
  48. */
  49. public function __construct(array $userProviders, $secret, $providerKey, array $options = array(), LoggerInterface $logger = null)
  50. {
  51. if (empty($secret)) {
  52. throw new \InvalidArgumentException('$secret must not be empty.');
  53. }
  54. if (empty($providerKey)) {
  55. throw new \InvalidArgumentException('$providerKey must not be empty.');
  56. }
  57. if (0 === \count($userProviders)) {
  58. throw new \InvalidArgumentException('You must provide at least one user provider.');
  59. }
  60. $this->userProviders = $userProviders;
  61. $this->secret = $secret;
  62. $this->providerKey = $providerKey;
  63. $this->options = array_merge($this->options, $options);
  64. $this->logger = $logger;
  65. }
  66. /**
  67. * Returns the parameter that is used for checking whether remember-me
  68. * services have been requested.
  69. *
  70. * @return string
  71. */
  72. public function getRememberMeParameter()
  73. {
  74. return $this->options['remember_me_parameter'];
  75. }
  76. /**
  77. * @deprecated Since version 2.8, to be removed in 3.0. Use getSecret() instead.
  78. */
  79. public function getKey()
  80. {
  81. @trigger_error(__METHOD__.'() is deprecated since Symfony 2.8 and will be removed in 3.0. Use getSecret() instead.', E_USER_DEPRECATED);
  82. return $this->getSecret();
  83. }
  84. /**
  85. * @return string
  86. */
  87. public function getSecret()
  88. {
  89. return $this->secret;
  90. }
  91. /**
  92. * Implementation of RememberMeServicesInterface. Detects whether a remember-me
  93. * cookie was set, decodes it, and hands it to subclasses for further processing.
  94. *
  95. * @return TokenInterface|null
  96. *
  97. * @throws CookieTheftException
  98. * @throws \RuntimeException
  99. */
  100. final public function autoLogin(Request $request)
  101. {
  102. if (null === $cookie = $request->cookies->get($this->options['name'])) {
  103. return;
  104. }
  105. if (null !== $this->logger) {
  106. $this->logger->debug('Remember-me cookie detected.');
  107. }
  108. $cookieParts = $this->decodeCookie($cookie);
  109. try {
  110. $user = $this->processAutoLoginCookie($cookieParts, $request);
  111. if (!$user instanceof UserInterface) {
  112. throw new \RuntimeException('processAutoLoginCookie() must return a UserInterface implementation.');
  113. }
  114. if (null !== $this->logger) {
  115. $this->logger->info('Remember-me cookie accepted.');
  116. }
  117. return new RememberMeToken($user, $this->providerKey, $this->secret);
  118. } catch (CookieTheftException $e) {
  119. $this->cancelCookie($request);
  120. throw $e;
  121. } catch (UsernameNotFoundException $e) {
  122. if (null !== $this->logger) {
  123. $this->logger->info('User for remember-me cookie not found.');
  124. }
  125. } catch (UnsupportedUserException $e) {
  126. if (null !== $this->logger) {
  127. $this->logger->warning('User class for remember-me cookie not supported.');
  128. }
  129. } catch (AuthenticationException $e) {
  130. if (null !== $this->logger) {
  131. $this->logger->debug('Remember-Me authentication failed.', array('exception' => $e));
  132. }
  133. }
  134. $this->cancelCookie($request);
  135. }
  136. /**
  137. * Implementation for LogoutHandlerInterface. Deletes the cookie.
  138. */
  139. public function logout(Request $request, Response $response, TokenInterface $token)
  140. {
  141. $this->cancelCookie($request);
  142. }
  143. /**
  144. * Implementation for RememberMeServicesInterface. Deletes the cookie when
  145. * an attempted authentication fails.
  146. */
  147. final public function loginFail(Request $request)
  148. {
  149. $this->cancelCookie($request);
  150. $this->onLoginFail($request);
  151. }
  152. /**
  153. * Implementation for RememberMeServicesInterface. This is called when an
  154. * authentication is successful.
  155. */
  156. final public function loginSuccess(Request $request, Response $response, TokenInterface $token)
  157. {
  158. // Make sure any old remember-me cookies are cancelled
  159. $this->cancelCookie($request);
  160. if (!$token->getUser() instanceof UserInterface) {
  161. if (null !== $this->logger) {
  162. $this->logger->debug('Remember-me ignores token since it does not contain a UserInterface implementation.');
  163. }
  164. return;
  165. }
  166. if (!$this->isRememberMeRequested($request)) {
  167. if (null !== $this->logger) {
  168. $this->logger->debug('Remember-me was not requested.');
  169. }
  170. return;
  171. }
  172. if (null !== $this->logger) {
  173. $this->logger->debug('Remember-me was requested; setting cookie.');
  174. }
  175. // Remove attribute from request that sets a NULL cookie.
  176. // It was set by $this->cancelCookie()
  177. // (cancelCookie does other things too for some RememberMeServices
  178. // so we should still call it at the start of this method)
  179. $request->attributes->remove(self::COOKIE_ATTR_NAME);
  180. $this->onLoginSuccess($request, $response, $token);
  181. }
  182. /**
  183. * Subclasses should validate the cookie and do any additional processing
  184. * that is required. This is called from autoLogin().
  185. *
  186. * @return UserInterface
  187. */
  188. abstract protected function processAutoLoginCookie(array $cookieParts, Request $request);
  189. protected function onLoginFail(Request $request)
  190. {
  191. }
  192. /**
  193. * This is called after a user has been logged in successfully, and has
  194. * requested remember-me capabilities. The implementation usually sets a
  195. * cookie and possibly stores a persistent record of it.
  196. */
  197. abstract protected function onLoginSuccess(Request $request, Response $response, TokenInterface $token);
  198. final protected function getUserProvider($class)
  199. {
  200. foreach ($this->userProviders as $provider) {
  201. if ($provider->supportsClass($class)) {
  202. return $provider;
  203. }
  204. }
  205. throw new UnsupportedUserException(sprintf('There is no user provider that supports class "%s".', $class));
  206. }
  207. /**
  208. * Decodes the raw cookie value.
  209. *
  210. * @param string $rawCookie
  211. *
  212. * @return array
  213. */
  214. protected function decodeCookie($rawCookie)
  215. {
  216. return explode(self::COOKIE_DELIMITER, base64_decode($rawCookie));
  217. }
  218. /**
  219. * Encodes the cookie parts.
  220. *
  221. * @return string
  222. *
  223. * @throws \InvalidArgumentException When $cookieParts contain the cookie delimiter. Extending class should either remove or escape it.
  224. */
  225. protected function encodeCookie(array $cookieParts)
  226. {
  227. foreach ($cookieParts as $cookiePart) {
  228. if (false !== strpos($cookiePart, self::COOKIE_DELIMITER)) {
  229. throw new \InvalidArgumentException(sprintf('$cookieParts should not contain the cookie delimiter "%s"', self::COOKIE_DELIMITER));
  230. }
  231. }
  232. return base64_encode(implode(self::COOKIE_DELIMITER, $cookieParts));
  233. }
  234. /**
  235. * Deletes the remember-me cookie.
  236. */
  237. protected function cancelCookie(Request $request)
  238. {
  239. if (null !== $this->logger) {
  240. $this->logger->debug('Clearing remember-me cookie.', array('name' => $this->options['name']));
  241. }
  242. $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']));
  243. }
  244. /**
  245. * Checks whether remember-me capabilities were requested.
  246. *
  247. * @return bool
  248. */
  249. protected function isRememberMeRequested(Request $request)
  250. {
  251. if (true === $this->options['always_remember_me']) {
  252. return true;
  253. }
  254. $parameter = ParameterBagUtils::getRequestParameterValue($request, $this->options['remember_me_parameter']);
  255. if (null === $parameter && null !== $this->logger) {
  256. $this->logger->debug('Did not send remember-me cookie.', array('parameter' => $this->options['remember_me_parameter']));
  257. }
  258. return 'true' === $parameter || 'on' === $parameter || '1' === $parameter || 'yes' === $parameter || true === $parameter;
  259. }
  260. }