使用2个实现UserInterface的实体进行身份验证

时间:2020-01-15 17:24:48

标签: php symfony symfony-security symfony5

是否可以有2个实体实现UserInterface

如何在我的后卫上使用它以使其在两个类中并使用同一防火墙进行检查?

这个想法是,公司可以拥有自己的CVTheque或与之共享(CVThequeCompany有OneToMany关系)。

我想拥有CandidateUser实体。

  • CVTheque-> OneToMany->候选人
  • 用户-> ManyToOne->公司。

CandidateUser将使用相同的登录表单在应用程序上进行身份验证。因此,我不知道是否有可能,以及如何在我的警卫认证器上实施此操作。

根据连接的用户实例(CandidateUser),他们将被重定向到自己的仪表板。

2 个答案:

答案 0 :(得分:5)

最近处理了类似的情况。 就我而言,只需创建一个 chain_provider 即可封装所需的所有实体:

providers:
    chain_provider:
        chain:
            providers: [provider_one, provider_two]
    provider_one:
        entity:
            class: App\Entity\ProviderOne
            property: username
    provider_two:
        entity:
            class: App\Entity\ProviderTwo
            property: email
security:
    firewalls:
        secured_area:
            # ...
            pattern: ^/login
            provider: chain_provider

答案 1 :(得分:1)

我相信有可能,让我们进行基本的用户身份验证并尝试对其进行调整

<?php

namespace App\Security;

use App\Entity\User;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Security;
use Symfony\Component\Security\Csrf\CsrfToken;
use Symfony\Component\EventDispatcher\GenericEvent;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Security\Http\Util\TargetPathTrait;
use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
use Symfony\Component\Security\Csrf\CsrfTokenManagerInterface;
use Symfony\Component\Security\Core\User\UserProviderInterface;
use Symfony\Contracts\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Exception\InvalidCsrfTokenException;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use Symfony\Component\Security\Guard\Authenticator\AbstractFormLoginAuthenticator;
use Symfony\Component\Security\Core\Exception\CustomUserMessageAuthenticationException;

class LoginAuthenticator extends AbstractFormLoginAuthenticator
{
    use TargetPathTrait;

    private $entityManager;
    private $urlGenerator;
    private $csrfTokenManager;
    private $encoder;

    public function __construct(
        EntityManagerInterface $entityManager,
        UrlGeneratorInterface $urlGenerator,
        CsrfTokenManagerInterface $csrfTokenManager,
        UserPasswordEncoderInterface $encoder)
    {
        $this->entityManager = $entityManager;
        $this->urlGenerator = $urlGenerator;
        $this->csrfTokenManager = $csrfTokenManager;
        $this->encoder = $encoder;
        $this->eventDispatcher = $eventDispatcher;
    }

    public function supports(Request $request)
    {
        return (
            'login' === $request->attributes->get('_route')&& $request->isMethod('POST') // here you need to specify the other login route if you want to have 2 seperate ones
        );
    }

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

        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(User::class)->findOneBy(['username' => $credentials['username']]);

        if (!$user) { // here look for user in the 2nd entity, if it will still be null throw the exception
            // fail authentication with a custom error
            throw new CustomUserMessageAuthenticationException('Username could not be found.');
        }

        return $user;
    }

    public function checkCredentials($credentials, UserInterface $user)
    {
        return $this->encoder->isPasswordValid($user, $credentials['password'], $user->getSalt());
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token, $providerKey)
    {        
        if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
            return new RedirectResponse($targetPath);
        }

        return new RedirectResponse($this->urlGenerator->generate('account_index'));
    }

    protected function getLoginUrl()
    {
        return $this->urlGenerator->generate('login');
    }
}

可能就是这样,我们将身份验证器更改为支持2条路由(登录一个,登录两个),如果第一个实体与用户名和密码不匹配,请尝试在另一个实体中查找用户,您也可以添加一个在请求侦听器中基于路由的隐藏输入或添加属性,可以使用RequestStack检索它,或者您要指示每个实体。