2021年2月10日星期三

Symfony 5: I can't login after logout

I am working with Symfony 5 with Easyadmin 3, but I have a problem.

Using Security Bundle and a make: auth, i set up a login and I can log in normally, the problem is that once I log out, I can't log in again with the same user unless i edit it.

src/Security/LoginFormAuthenticator:

<?php    namespace App\Security;    use App\Entity\Persona;  use Doctrine\ORM\EntityManagerInterface;  use Symfony\Component\HttpFoundation\RedirectResponse;  use Symfony\Component\HttpFoundation\Request;  use Symfony\Component\Routing\Generator\UrlGeneratorInterface;  use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;  use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;  use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;  use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;  use Symfony\Component\Security\Core\Security;  use Symfony\Component\Security\Core\User\UserInterface;  use Symfony\Component\Security\Core\User\UserProviderInterface;  use Symfony\Component\Security\Csrf\CsrfToken;  use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;  use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;  use Symfony\Component\Security\Guard\PasswordAuthenticatedInterface;  use Symfony\Component\Security\Http\Util\TargetPathTrait;    class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface  {      use TargetPathTrait;        public const LOGIN_ROUTE = 'app_login';        private $entityManager;      private $urlGenerator;      private $csrfTokenManager;      private $passwordEncoder;        public function __construct(EntityManagerInterface $entityManager, UrlGeneratorInterface $urlGenerator, CsrfTokenManagerInterface $csrfTokenManager, UserPasswordEncoderInterface $passwordEncoder)      {          $this->entityManager = $entityManager;          $this->urlGenerator = $urlGenerator;          $this->csrfTokenManager = $csrfTokenManager;          $this->passwordEncoder = $passwordEncoder;      }        public function supports(Request $request)      {          return self::LOGIN_ROUTE === $request->attributes->get('_route')              && $request->isMethod('POST');      }        public function getCredentials(Request $request)      {          $credentials = [              'email' => $request->request->get('email'),              'password' => $request->request->get('password'),              'csrf_token' => $request->request->get('_csrf_token'),          ];          $request->getSession()->set(              Security::LAST_USERNAME,              $credentials['email']          );            return $credentials;      }        public function getUser($credentials, UserProviderInterface $userProvider)      {          $token = new CsrfToken('authenticate', $credentials['csrf_token']);          if (!$this->csrfTokenManager->isTokenValid($token)) {              throw new InvalidCsrfTokenException();          }            $user = $this->entityManager->getRepository(Persona::class)->findOneBy(['email' => $credentials['email']]);            if (!$user) {              // fail authentication with a custom error              throw new CustomUserMessageAuthenticationException('No se encontro cuenta con ese Email.');          }            return $user;      }        public function checkCredentials($credentials, UserInterface $user)      {          return $this->passwordEncoder->isPasswordValid($user, $credentials['password']);      }        /**       * Used to upgrade (rehash) the user's password automatically over time.       */      public function getPassword($credentials): ?string      {          return $credentials['password'];      }        public function onAuthenticationSuccess(Request $request, TokenInterface $token, string $providerKey)      {          if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {              return new RedirectResponse($targetPath);          }            // For example : return new RedirectResponse($this->urlGenerator->generate('some_route'));          return new RedirectResponse('admin'); //Ni bien se loguee donde ira      }        protected function getLoginUrl()      {          return $this->urlGenerator->generate(self::LOGIN_ROUTE);      }  }  

src/Controller/SecurityController:

    <?php            namespace App\Controller;            use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;      use Symfony\Component\HttpFoundation\Response;      use Symfony\Component\Routing\Annotation\Route;      use Symfony\Component\Security\Http\Authentication\AuthenticationUtils;            class SecurityController extends AbstractController      {          /**           * @Route("/login", name="app_login")           */          public function login(AuthenticationUtils $authenticationUtils): Response          {              // if ($this->getUser()) {              //     return $this->redirectToRoute('target_path');              // }                    // get the login error if there is one              $error = $authenticationUtils->getLastAuthenticationError();              // last username entered by the user              $lastUsername = $authenticationUtils->getLastUsername();                    return $this->render('security/login.html.twig', ['last_username' => $lastUsername, 'error' => $error]);          }                /**           * @Route("/logout", name="app_logout")           */          public function logout()          {              throw new \LogicException('This method can be blank - it will be intercepted by the logout key on your firewall.');          }      }  

Config/Package/Security.yaml

security:      encoders:          Symfony\Component\Security\Core\User\User: bcrypt          App\Entity\Persona:              algorithm: auto        # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers      providers:          # used to reload user from session & other features (e.g. switch_user)          app_user_provider:              entity:                  class: App\Entity\Persona                  property: email      firewalls:          dev:              pattern: ^/(_(profiler|wdt)|css|images|js)/              security: false          main:              anonymous: true              lazy: true              provider: app_user_provider              guard:                  authenticators:                      - App\Security\LoginFormAuthenticator              logout:                  path: app_logout                  # where to redirect after logout                  target: /login                  #target: app_any_route                # activate different ways to authenticate              # https://symfony.com/doc/current/security.html#firewalls-authentication                # https://symfony.com/doc/current/security/impersonating_user.html              # switch_user: true        # Easy way to control access for large sections of your site      # Note: Only the *first* access control that matches will be used      access_control:          # - { path: ^/admin, roles: ROLE_ADMIN }          # - { path: ^/profile, roles: ROLE_USER }  
https://stackoverflow.com/questions/66148430/symfony-5-i-cant-login-after-logout February 11, 2021 at 11:38AM

没有评论:

发表评论