Symfony 3-手动处理登录过程

问题描述 投票:1回答:1

我尝试使用如下定义的服务来手动处理整个登录过程

<?php

namespace StandardBundle\Security;

use \PDO;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
use Symfony\Component\Security\Core\Encoder\EncoderFactoryInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;

class AuthenticateUser
{
    private $sesion;
    private $security;
    private $em;
    private $factory;

    public function __construct(SessionInterface $session, TokenStorageInterface $security, EntityManagerInterface $em, EncoderFactoryInterface $factory)
    {
        $this->session = $session;
        $this->security   = $security;
        $this->em      = $em;
        $this->factory = $factory;
    }

    public function identification($login, $passw)
    {
        if( ('' === $login || null === $login) || ('' === $passw || null === $passw) ) {
            throw new \InvalidArgumentException('Login and password can\'t be empty');
        }

        // getRepo
        $repo = $this->em->getRepository("StandardBundle:User");

        // getUser
        $user = $repo->findOneBy(array('username' => $login));

        // check user exists
        if(!$user){
            return false;
        }

        // get encoder
        $encoder = $this->factory->getEncoder($user);

        // get salt
        $salt = $user->getSalt();

        // Check password is valid
        if(!$encoder->isPasswordValid($user->getPassword(), $passw, $salt)) {
            throw new BadCredentialsException('Bad credentials');
        }

        // generate token
        $token = new UsernamePasswordToken($user, $user->getPassword(), 'main', array('ROLE_VISITEUR'));
        // set token
        $this->security->setToken($token);

        // If the firewall name is not main, then the set value would be instead:
        // $this->get('session')->set('_token_XXXFIREWALLNAMEXXX', serialize($token));
        $this->session->set('_token_main', serialize($token));
        // save
        $this->session->save();
    }
}

这是控制器中的loginAction

<?php

public function loginAction(Request $request)
  {
    if ($this->get('security.authorization_checker')->isGranted('IS_AUTHENTICATED_FULLY')) {
      return $this->redirectToRoute('home');
    }

    if ($request->isMethod('POST')){
        $authenticateUser = $this->get("standard.authenticate_user");
        $authenticateUser->identification('fakeuser','myfakepassw');
    }

    $authenticationUtils = $this->get('security.authentication_utils');

    // get the login error if there is one
    $error = $authenticationUtils->getLastAuthenticationError();

    $lastUsername = $authenticationUtils->getLastUsername();

    $defaultData = array(
      //'action' => $this->generateUrl('login_check')
      'action' => $this->generateUrl('login_' . $request->getLocale())
    );

    $form = $this->createForm(LoginForm::class, array(), $defaultData);
    $form->get('_username')->setData($lastUsername);
    $form->get('_failure_path')->setData($request->getPathInfo());

    $form->handleRequest($request);

    if (!is_null($error)) {
      $form->addError(
        new FormError($error->getMessage())
      );      
    }

    return $this->render('@Standard/login.html.twig', array(
      'form' => $form->createView()
    ));
  }

它似乎运行良好,但是如果提供了不正确的信息,我的服务会抛出BadCredentialsException,它不会被symfony捕获,并且无法通过]返回

$authenticationUtils = $this->get('security.authentication_utils');

// get the login error if there is one
$error = $authenticationUtils->getLastAuthenticationError();

预期enter image description here得到enter image description here

如何告诉symfony以错误形式显示我的异常?

php symfony
1个回答
0
投票

您是否在模板上显示了表单错误?{{ form_errors(form) }}this ...

或者您可以使用FormEvents(例如this)对表单执行凭据检查。然后处理类似this的表格,这意味着如果凭据有效,则表格有效(然后登录用户并重定向),否则显示表格错误。

© www.soinside.com 2019 - 2024. All rights reserved.