src/Security/UserAuthenticator.php line 36

Open in your IDE?
  1. <?php
  2. namespace App\Security;
  3. use App\Entity\User;
  4. use Symfony\Component\HttpFoundation\RedirectResponse;
  5. use Symfony\Component\HttpFoundation\Request;
  6. use Symfony\Component\HttpFoundation\Response;
  7. use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
  8. use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
  9. use Symfony\Component\Security\Core\Security;
  10. use Symfony\Component\Security\Http\Authenticator\AbstractLoginFormAuthenticator;
  11. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\CsrfTokenBadge;
  12. use Symfony\Component\Security\Http\Authenticator\Passport\Badge\UserBadge;
  13. use Symfony\Component\Security\Http\Authenticator\Passport\Credentials\PasswordCredentials;
  14. use Symfony\Component\Security\Http\Authenticator\Passport\Passport;
  15. use Symfony\Component\Security\Http\Util\TargetPathTrait;
  16. class UserAuthenticator 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): Passport
  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->request->get('_csrf_token')),
  34.             ]
  35.         );
  36.     }
  37.     public function onAuthenticationSuccess(Request $requestTokenInterface $tokenstring $firewallName): ?Response
  38.     {
  39.         // if ($targetPath = $this->getTargetPath($request->getSession(), $firewallName)) {
  40.         //     return new RedirectResponse($targetPath);
  41.         // }
  42.             return new RedirectResponse($this->urlGenerator->generate('app_login'));
  43.         // For example:
  44.         //return new RedirectResponse($this->urlGenerator->generate('some_route'));
  45.         throw new \Exception('TODO: provide a valid redirect inside '.__FILE__);
  46.     }
  47.     protected function getLoginUrl(Request $request): string
  48.     {
  49.         return $this->urlGenerator->generate(self::LOGIN_ROUTE);
  50.     }
  51. }