How to access the user Token in an injected service to reencode passwords?

后端 未结 1 1647
野的像风
野的像风 2021-01-21 02:51

I have the below code where I am trying to re-encode passwords as users log in (the database has bee migrated form a legacy website). However, I\'m not sure what I\'m doing wron

相关标签:
1条回答
  • 2021-01-21 03:26

    In your services, you can only access what dependencies you've injected.

    So, to access the current user object, you need to pass it as argument:

    service:

    club.password_rehash:
        class: AppBundle\Service\PasswordRehash
        arguments: [ "@security.token_storage" ]
    

    Constructor:

    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
    
    class HubAuthenticator extends \Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder implements PasswordEncoderInterface
    {
        private $storage;
    
        function __construct($cost = 13, TokenStorageInterface $storage)
        {
            parent::__construct($cost);
    
            $this->storage = $storage;
            // Now you can use:
            // $user = $this->storage->getToken()->getUser();
        }
    }
    

    Then, to access the second service, same way, inject it.

    Add it to the service arguments:

    club.password_rehash:
        class: AppBundle\Service\PasswordRehash
        arguments: [ "@security.token_storage", "@club.password_rehash" ]
    

    Add it to your constructor:

    private $storage;
    private $passwordRehash
    
    function __construct($cost = 13, TokenStorageInterface $storage, PasswordRehash $passwordRehash)
    {
        parent::__construct($cost);
    
        $this->storage = $storage;
        $this->passwordRehash = $passwordRehash;
        // Now you can use:
        // $this->passwordRehash->rehash(...);
    }
    

    Hope this helps you.

    0 讨论(0)
提交回复
热议问题