src/Security/LoginFormAuthenticator.php line 19

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use Symfony\Component\HttpFoundation\RedirectResponse;
  4. use Symfony\Component\HttpFoundation\Request;
  5. use Symfony\Component\HttpFoundation\Response;
  6. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  7. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  8. use Symfony\Component\Security\Core\Security;
  9. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  10. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  11. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  14. use Symfony\Component\Security\Http\Authenticator\Passport\PassportInterface;
  15. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  16. class LoginFormAuthenticator extends AbstractLoginFormAuthenticator
  17. {
  18. use TargetPathTrait;
  19. public const LOGIN_ROUTE = 'app_login';
  20. private UrlGeneratorInterface $urlGenerator;
  21. public function __construct(UrlGeneratorInterface $urlGenerator)
  22. {
  23. $this->urlGenerator = $urlGenerator;
  24. }
  25. public function authenticate(Request $request): PassportInterface
  26. {
  27. $Username = $request->request->get('username', '');
  28. $request->getSession()->set(Security::LAST_USERNAME, $Username);
  29. return new Passport(
  30. new UserBadge($Username),
  31. new PasswordCredentials($request->request->get('password', '')),
  32. [
  33. new CsrfTokenBadge('authenticate', $request->get('_csrf_token')),
  34. ]
  35. );
  36. }
  37. public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $firewallName): ?Response
  38. {
  39. if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
  40. return new RedirectResponse($targetPath);
  41. }
  42. // For example:
  43. return new RedirectResponse($this->urlGenerator->generate('admin'));
  44. throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  45. }
  46. protected function getLoginUrl(Request $request): string
  47. {
  48. return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  49. }
  50. public function supports(Request $request): bool
  51. {
  52. return $request->isMethod('POST') && $this->getLoginUrl($request) === $request->getPathInfo();
  53. }
  54. }