我有以下代码,我试图在用户登录时重新编码密码(数据库已从旧网站迁移)。但是,我不确定我做错了什么,因为我不断出错:
尝试调用类“AppBundle \ Service \ HubAuthenticator”的名为“forward”的未定义方法。
我的设置如下:
security:
encoders:
AppBundle\Entity\Member:
id: club.hub_authenticator
services:
//This should be central service than then calls the second
club.hub_authenticator:
class: AppBundle\Service\HubAuthenticator
club.password_rehash:
class: AppBundle\Service\PasswordRehash
namespace AppBundle\Service;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
class HubAuthenticator extends \Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder implements PasswordEncoderInterface
{
function __construct($cost=13)
{
parent::__construct($cost);
}
function isPasswordValid($encoded, $raw, $salt)
{
// Test for legacy authentication (and conditionally rehash the password stored in the database if true)
if ($this->comparePasswords($encoded, sha1("saltA".$raw."saltB"))) {
$this->forward('club.password_rehash:rehash');
}
// Test for Symfony's Bcrypt authentication (any passwords just rehashed in previous step should work here)
if (parent::isPasswordValid($cost=13, $encoded,$raw,$salt)) return true ;
}
}
namespace AppBundle\Service;
use Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface;
class PasswordRehash extends \Symfony\Component\Security\Core\Encoder\BCryptPasswordEncoder
{
// Customises BCryptPasswordEncoder class to use legacy SHA method
function rehash($member, $raw, $salt)
{
//Salt is null as Symfony documentation says it is better to generate a new one
parent::encodePassword($member->getPlainPassword, $salt=null ) ;
}
}
我猜测的问题是,我误解了我可以使用的对象。我的理解是此时用户尚未经过身份验证,因此尝试并删除了以下尝试:
尝试将$member
注入HubAuthenticator
服务:
function __construct($cost=13)
{
parent::__construct($cost, \Member $member);
}
尝试重新使用plainpassword时:
$this->get('security.context')->getToken()->getUser()->getPlainPassword();
答案 0 :(得分:2)
在您的服务中,您只能访问您注入的依赖项。
因此,要访问当前用户对象,需要将其作为参数传递:
服务:
club.password_rehash:
class: AppBundle\Service\PasswordRehash
arguments: [ "@security.token_storage" ]
构造
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();
}
}
然后,以同样的方式访问第二个服务,注入它。
将其添加到服务参数:
club.password_rehash:
class: AppBundle\Service\PasswordRehash
arguments: [ "@security.token_storage", "@club.password_rehash" ]
将其添加到构造函数中:
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(...);
}
希望这会对你有所帮助。