Manual authentication check Symfony 2

后端 未结 5 1330
我在风中等你
我在风中等你 2021-02-01 07:53

I\'m working on a Symfony 2 application where the user must select a profile during the login process.

Users may have multiples profiles to work with and they only know

5条回答
  •  星月不相逢
    2021-02-01 08:13

    You could do something like this to retrieve the user and manually test the password -

    $username = trim($this->getRequest()->query->get('username'));
    $password = trim($this->getRequest()->query->get('password'));
    
    $em = $this->get('doctrine')->getEntityManager();
    $query = $em->createQuery("SELECT u FROM \Some\Bundle\Entity\User u WHERE u.username = :username");
    $query->setParameter('username', $username);
    $user = $query->getOneOrNullResult();
    
    if ($user) {
      // Get the encoder for the users password
      $encoder_service = $this->get('security.encoder_factory');
      $encoder = $encoder_service->getEncoder($user);
      $encoded_pass = $encoder->encodePassword($password, $user->getSalt());
    
      if ($user->getPassword() == $encoded_pass) {
        // Get profile list
      } else {
        // Password bad
      }
    } else {
      // Username bad
    }
    

    Once you've got your profile back from the client, you can perform the login manually in the AJAX server controller easily enough too -

    // Get the security firewall name, login
    $providerKey = $this->container->getParameter('fos_user.firewall_name');
    $token = new UsernamePasswordToken($user, $password, $providerKey, $user->getRoles());
    $this->get("security.context")->setToken($token);
    
    // Fire the login event
    $event = new InteractiveLoginEvent($this->getRequest(), $token);
    $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);
    

    Might need a few use lines -

    use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;
    use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
    

提交回复
热议问题