Manual authentication check Symfony 2

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

    I used the code from @Jordon and @Potor Polak to wrap the logic in a standalone service that used the current access token to validate the password. Maybe some needs this:

    services.yml:

    app.validator.manual_password:
        class: AppBundle\Service\ManualPasswordValidator
        arguments:
            - '@security.token_storage'
            - '@security.encoder_factory'
    

    ManualPasswordValidator.php:

    encoderFactory = $encoderFactory;
            $this->tokenStorage = $tokenStorage;
        }
    
        /**
         * @param $password
         * @return bool
         */
        public function passwordIsValidForCurrentUser($password)
        {
            $token = $this->tokenStorage->getToken();
    
            if ($token) {
                $user = $token->getUser();
    
                if ($user) {
                    $encoder = $this->encoderFactory->getEncoder($user);
    
                    if ($encoder->isPasswordValid($user->getPassword(), $password, $user->getSalt())) {
                        return true;
                    }
                }
            }
    
            return false;
        }
    }
    

    After this you can inject the ManualPasswordValidator wherever you want and use it like:

    $password        = $request->get('password');
    $passwordIsValid = $this->manualPasswordValidator->passwordIsValidForCurrentUser($password);
    

提交回复
热议问题