AbstractLoginFormAuthenticator.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  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\Authenticator;
  11. use Symfony\Component\HttpFoundation\RedirectResponse;
  12. use Symfony\Component\HttpFoundation\Request;
  13. use Symfony\Component\HttpFoundation\Response;
  14. use Symfony\Component\Security\Core\Exception\AuthenticationException;
  15. use Symfony\Component\Security\Core\Security;
  16. use Symfony\Component\Security\Http\EntryPoint\AuthenticationEntryPointInterface;
  17. /**
  18. * A base class to make form login authentication easier!
  19. *
  20. * @author Ryan Weaver <ryan@symfonycasts.com>
  21. *
  22. * @experimental in 5.2
  23. */
  24. abstract class AbstractLoginFormAuthenticator extends AbstractAuthenticator implements AuthenticationEntryPointInterface, InteractiveAuthenticatorInterface
  25. {
  26. /**
  27. * Return the URL to the login page.
  28. */
  29. abstract protected function getLoginUrl(Request $request): string;
  30. /**
  31. * {@inheritdoc}
  32. *
  33. * Override to change the request conditions that have to be
  34. * matched in order to handle the login form submit.
  35. *
  36. * This default implementation handles all POST requests to the
  37. * login path (@see getLoginUrl()).
  38. */
  39. public function supports(Request $request): bool
  40. {
  41. return $request->isMethod('POST') && $this->getLoginUrl($request) === $request->getPathInfo();
  42. }
  43. /**
  44. * Override to change what happens after a bad username/password is submitted.
  45. */
  46. public function onAuthenticationFailure(Request $request, AuthenticationException $exception): Response
  47. {
  48. if ($request->hasSession()) {
  49. $request->getSession()->set(Security::AUTHENTICATION_ERROR, $exception);
  50. }
  51. $url = $this->getLoginUrl($request);
  52. return new RedirectResponse($url);
  53. }
  54. /**
  55. * Override to control what happens when the user hits a secure page
  56. * but isn't logged in yet.
  57. */
  58. public function start(Request $request, AuthenticationException $authException = null): Response
  59. {
  60. $url = $this->getLoginUrl($request);
  61. return new RedirectResponse($url);
  62. }
  63. public function isInteractive(): bool
  64. {
  65. return true;
  66. }
  67. }