简体   繁体   English

无法从数据库 symfony 4 中验证用户重定向到同一登录页面

[英]not able to verify user from database symfony 4 redirecting to same login page

In the basic login form I'm trying to check if the user from the database I inserted which I entered in the login form but the page is redirecting to the same page because there is a error in my getUser or checkCredentials from LoginAuthenticator.在基本登录表单中,我试图检查我插入的数据库中的用户是否在登录表单中输入,但页面重定向到同一页面,因为我的 getUser 或来自 LoginAuthenticator 的 checkCredentials 中存在错误。 I'm confused what's wrong in my code.我很困惑我的代码有什么问题。
LoginAuthenticator登录验证器

<?php

namespace App\Security;

use App\Repository\UsersRepository;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;

class LogAuthenticator extends AbstractFormLoginAuthenticator
{

    private $usersRepository;
    private $router;

    public function __construct(UsersRepository $usersRepository, RouterInterface $router){

        $this->usersRepository = $usersRepository;
        $this->router = $router;
    }

    public function supports(Request $request)
    {
       return $request->attributes->get('_route') === 'app_login'
           && $request->isMethod('POST');
    }

    public function getCredentials(Request $request)
    {
      $credentials = [
        'email' => $request->request->get('user_email'),
        'password' => $request->request->get('password')
      ];
      $request ->getSession()->set(
          Security::LAST_USERNAME,
          $credentials['email']
      );

      return $credentials;
    }

    public function getUser($credentials, UserProviderInterface $userProvider)
    {
        $this->usersRepository->findOneBy(['user_email' =>$credentials['email']]);
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return true;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {
        return $this->router->generate('app_homepage');
    }

    protected function getLoginUrl()
    {
        return $this->router->generate('app_login');
    }
}

LoginController登录控制器

<?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 LoginController 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.');
    }
}

userRepository用户库

<?php

namespace App\Repository;

use App\Entity\User;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;

/**
 * @method User|null find($id, $lockMode = null, $lockVersion = null)
 * @method User|null findOneBy(array $criteria, array $orderBy = null)
 * @method User[]    findAll()
 * @method User[]    findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
 */
class UserRepository extends ServiceEntityRepository
{
    public function __construct(ManagerRegistry $registry)
    {
        parent::__construct($registry, User::class);
    }

    // /**
    //  * @return User[] Returns an array of User objects
    //  */
    /*
    public function findByExampleField($value)
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.exampleField = :val')
            ->setParameter('val', $value)
            ->orderBy('u.id', 'ASC')
            ->setMaxResults(10)
            ->getQuery()
            ->getResult()
        ;
    }
    */

    /*
    public function findOneBySomeField($value): ?User
    {
        return $this->createQueryBuilder('u')
            ->andWhere('u.exampleField = :val')
            ->setParameter('val', $value)
            ->getQuery()
            ->getOneOrNullResult()
        ;
    }
    */
}

Security.yaml安全.yaml

security:
    encoders:
        App\Entity\Users:
            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\Users
                property: email
    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: lazy
            provider: app_user_provider

            logout:
                path: app_logout
            guard:
                authenticators:
                    - App\Security\LoginAuthenticator

                # where to redirect after logout
                # 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 }


enter image description here在此处输入图片说明

You are using the wrong user provider, right now your firewall uses the memory provider with a null value:您使用了错误的用户提供程序,现在您的防火墙使用具有null值的memory提供程序:

security:
    ...
    providers:
        users_in_memory: { memory: null }
    ...

When you want to retrieve users from the database you should use entity provider:当您想从数据库中检索用户时,您应该使用entity提供程序:

# config/packages/security.yaml
security:
    # ...

    providers:
        users:
            entity:
                # the class of the entity that represents users
                class: 'App\Entity\User'
                # the property to query by - e.g. username, email, etc
                property: 'username'
                # optional: if you're using multiple Doctrine entity
                # managers, this option defines which one to use
                # manager_name: 'customer'

    # ...

https://symfony.com/doc/4.4/security/user_provider.html#security-entity-user-provider https://symfony.com/doc/4.4/security/user_provider.html#security-entity-user-provider

Full documentation can be found here: https://symfony.com/doc/4.4/security.html完整文档可以在这里找到: https : //symfony.com/doc/4.4/security.html

Edit: I just noticed you also set the enable_authenticator_manager in your security.yaml .编辑:我刚刚注意到您还在security.yaml设置了enable_authenticator_manager If your project runs Symfony 4.x this will not work because it was introduced in Symfony 5.1.如果您的项目运行 Symfony 4.x,这将不起作用,因为它是在 Symfony 5.1 中引入的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM