Symfony 5/登录登录/Guard认证 [英] Symfony 5 / login-signin / Guard authentication

查看:80
本文介绍了Symfony 5/登录登录/Guard认证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须在同一页面中使用LoginForm和RegistrationForm

I have to use LoginForm and RegistrationForm in the same page

我正在使用make:auth提供的经典Guard身份验证

I m using classic Guard Authentication provided by make:auth

基于 Symfony 5-同一页面上的多个表单,我已经创建了LoginFormType并复制了RegistrationController中的内容.

Based on Symfony 5 - Multiples forms on same page, I have created LoginFormType and copy what I have in RegistrationController.

登录和注册均失败.

security.yaml:

security.yaml :

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
            target: app_login

        remember_me:
            secret: '%kernel.secret%'
            lifetime: 604800 # 1 week in seconds
            path: /

Security/LoginFormAuthenticator.php

Security/LoginFormAuthenticator.php

class LoginFormAuthenticator extends AbstractFormLoginAuthenticator implements PasswordAuthenticatedInterface{
use TargetPathTrait;

public const LOGIN_ROUTE = 'app_login';

/**
 * @var $entityManager EntityManagerInterface
 */
private $entityManager;

/**
 * @var UrlGeneratorInterface
 */
private $urlGenerator;

/**
 * @var $csrfTokenManager CsrfTokenManagerInterface
 */
private $csrfTokenManager;

/**
 * @var $passwordEncoder UserPasswordEncoderInterface
 */
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(User::class)->findOneBy(['email' => $credentials['email']]);

    if (!$user) {
        // fail authentication with a custom error
        throw new CustomUserMessageAuthenticationException('Email could not be found.');
    }

    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, $providerKey)
{
    dd('hello');
    if ($targetPath = $this->getTargetPath($request->getSession(), $providerKey)) {
        return new RedirectResponse($targetPath);
    }

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

protected function getLoginUrl()
{
    return $this->urlGenerator->generate(self::LOGIN_ROUTE);
}

}

SecurityController登录方法

SecurityController login method

public function login(
    Request $request,
    AuthenticationUtils $authenticationUtils,
    GuardAuthenticatorHandler $guardAuthenticatorHandler,
    LoginFormAuthenticator $loginFormAuthenticator
): Response {
    if ($this->getUser()) {
        return $this->redirectToRoute('dashboard');
    }

    // LOGIN
    $userToLogIn = new User();
     $director = new Director();
    $loginForm = $this->createForm(LoginFormType::class, $userToLogIn);
     $registrationForm = $this->createForm(RegistrationFormType::class, $director);

    if ($request->isMethod(Request::METHOD_POST)) {
        $loginForm->handleRequest($request);
        $registrationForm->handleRequest($request);

        dump($request->get('signIn'));
        dd($request->get('signUp'));
    }

    // 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,
        'loginForm' => $loginForm->createView(),
        'registrationForm' => $registrationForm->createView()
    ]);
}

我正在使用:Symfony 5.1.3PHP 7.3.20(由于某些供应商的不兼容,我尚未升级到7.4)我正在使用Symfony本地服务器,没有nginx或apache我没有任何.htaccess文件

I m using: Symfony 5.1.3 PHP 7.3.20 ( I m not upgraded to 7.4 yet for non compatibility of some vendors) I m using Symfony local server, no nginx or apache I don't have any .htaccess file

我在搜索时发现与会话有关,这就是为什么要添加

When I m googling that, I found that could be relative to session, that's why I added

framework.yaml:

framework.yaml :

framework:
//...

session:
    //...
    save_path: '%kernel.project_dir%/var/sessions/%kernel.environment%'

    

登录和注册之前分别进行过

但是现在当我刚访问网站上的任何页面时我在登录或注册之前遇到了错误

But now when I just visit any page in my site I have this errors before login or register

并且当我尝试登录时此

登录后出错

有任何帮助吗?

推荐答案

我通过在登录模板中呈现注册控制器来解决了这个问题

I solved the problem by rendering the registration controller in the login template

login.html.twig

login.html.twig

// login form
....
{{ render(controller('App\\Controller\\RegistrationController::register')) }}

这篇关于Symfony 5/登录登录/Guard认证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆