Manual authentication check Symfony 2

后端 未结 5 1323
我在风中等你
我在风中等你 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:16

    A problem with @Jordon's code is that it will not work with hashing algorithms that generate different hashes for the same password (such as bcrypt that stories internally its parameters, both the number of iterations and the salt). It is more correct to use isPasswordValid of the Encoder for comparing passwords.

    Here is the improved code that works fine with bcrypt:

    $username = trim($this->getRequest()->query->get('username'));
    $password = trim($this->getRequest()->query->get('password'));
    
    $em = $this->get('doctrine')->getManager();
    $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);
    
      // Note the difference
      if ($encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
        // Get profile list
      } else {
        // Password bad
      }
    } else {
      // Username bad
    }
    

提交回复
热议问题