src/Security/ProviderAuthenticator.php line 18

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\Util\TargetPathTrait;
  15. class ProviderAuthenticator extends AbstractLoginFormAuthenticator
  16. {
  17.     use TargetPathTrait;
  18.     public const LOGIN_ROUTE 'app_login';
  19.     private UrlGeneratorInterface $urlGenerator;
  20.     public function __construct(UrlGeneratorInterface $urlGenerator)
  21.     {
  22.         $this->urlGenerator $urlGenerator;
  23.     }
  24.     public function authenticate(Request $request): Passport
  25.     {
  26.         $username $request->request->get('username''');
  27.         $request->getSession()->set(Security::LAST_USERNAME$username);
  28.         $test = new Passport(
  29.             new UserBadge($username),
  30.             new PasswordCredentials($request->request->get('password''')),
  31.             [
  32.                 new CsrfTokenBadge('authenticate'$request->request->get('_csrf_token')),
  33.             ]
  34.         );
  35.         return $test;
  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.         // For example:
  43.         //return new RedirectResponse($this->urlGenerator->generate('some_route'));
  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. }