dongmou5628
2014-08-16 00:15 阅读 19
已采纳

在Symfony2应用程序中验证用户

This is going to sound very weird but kindly bear with me. I have built a symfony2 application which runs pretty well on the web.

Some users in the field are having so much trouble accessing the application on their phones in the field because we all know how heavy symfony is. The situation is so bad i'm forced to heavily scale down their access to just a four page access with just three php files, 1 for authentication, one for data entry and one for viewing their entries, all these without using symfony2 but plain php.

Now to my question, how do i check password against database password/salt?

I'm using FOSUserBundle for security

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

2条回答 默认 最新

  • 已采纳
    douwei7501 douwei7501 2014-08-16 00:48

    Are you sure you're using FOSUserBundle for security? I think you'll find you're using the core SecurityBundle for that. The way the user's password is stored will depend on how you have configured the security system.

    The MessageDigestPasswordEncoder is what is used to encode the passwords. From looking at that code you can replicated it as needed. The gist of it is merge the password and salt ($password.'{'.$salt.'}') and then run it through PHP's hash function hash($this->algorithm, $salted, true) for however many iterations are needed.

    Although, not specifically related to the question you asked, I'm a little confused as to what you mean by having to scale back the PHP for mobile users? Server page generation will take just as long for mobile as desktop users so why are you reimplementing outside of the symfony framework?

    点赞 评论 复制链接分享
  • duanbin4847 duanbin4847 2014-08-16 00:48

    you can use user manager to check user credentials validity. i've created the following function for such mission.

    /**
     * authorize user by username and password
     * 
     * @param string $username
     * @param string $raw_password
     */
    public function authUserByUsernamePassword($username, $raw_password) {
        $userManager = $this->container->get('fos_user.user_manager');
        $user = $userManager->findUserByUsername($username);
    
        // username not found
        if (!$user) {
            throw new \Exception("User with username: $username not found!", 0);
        }
    
        $encoder_service = $this->container->get('security.encoder_factory');
        $encoder = $encoder_service->getEncoder($user);
        $encoded_pass = $encoder->encodePassword($raw_password, $user->getSalt());
    
        if($encoded_pass != $user->getPassword()){
            throw new \Exception("wrong password!", 0);
        }
    
        // Get UsernamePasswordToken
        $token = new UsernamePasswordToken($user, $user->getPassword(), 'main', $user->getRoles());
        // Set token
        $this->authUserByToken($token);
    
        return $this->getUserToken($user);
    }
    
    点赞 评论 复制链接分享

相关推荐