簡體   English   中英

Symfony 5 / login-signin / Guard 認證

[英]Symfony 5 / login-signin / Guard authentication

我必須在同一頁面中使用 LoginForm 和 RegistrationForm

我正在使用 make:auth 提供的經典 Guard 身份驗證

基於Symfony 5 - Multiples forms on same page ,我創建了 LoginFormType 並復制了我在 RegistrationController 中的內容。

登錄和注冊均失敗。

安全性.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: /

安全/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);
}

}

安全控制器登錄方法

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()
    ]);
}

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

當我在谷歌上搜索時,我發現它可能與 session 相關,這就是我添加的原因

框架.yaml:

framework:
//...

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

    

登錄和注冊之前分開工作

但是現在當我訪問我網站中的任何頁面時,我都有這個

登錄或注冊前的錯誤

當我嘗試登錄時

登錄后出錯

請問有什么幫助嗎???

我通過在登錄模板中渲染注冊 controller 解決了這個問題

login.html.twig

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM