我有令牌实体,用于存储api_key
并与用户实体具有一对一关系:
AppBundle\Entity\Token:
type: entity
table: null
oneToOne:
user:
targetEntity: User
id:
id:
type: integer
id: true
generator:
strategy: AUTO
fields:
apiKey:
type: string
length: 255
dateCreated:
type: datetime
column: date_created
dateExpired:
type: datetime
column: date_expired
我正在使用simple_preauth
侦听器进行登录。登录成功后,我在登录页面上调用TokenGenerator服务:
public function loginAction()
{
$user = $this->get('security.token_storage')->getToken()->getUser();
if ($user instanceof User) {
$apiKey = $this->get('app_bundle.token_generator')->createApiKey()->getApiKey();
return new Response($apiKey);
}
throw new AuthenticationException('Authentication failed');
}
TokenGenerator返回api密钥,我可以在其他页面上使用它进行身份验证。此外,此服务还会将api_key
保存到令牌表中:
use Doctrine\ORM\EntityRepository as TokenRepository;
use Doctrine\ORM\EntityManager;
use AppBundle\Entity\Token;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class TokenGenerator
{
private $user;
public function __construct(
EntityManager $em,
TokenRepository $tokenRepository,
TokenStorageInterface $tokenStorage
) {
$this->em = $em;
$this->tokenRepository = $tokenRepository;
$this->tokenStorage = $tokenStorage;
}
public function getApiKey()
{
return $this->apiKey;
}
public function createApiKey()
{
$this->apiKey = password_hash(
uniqid(mt_rand(), true), PASSWORD_DEFAULT, array('cost' => '10')
);
$this->user = $this->tokenStorage->getToken()->getUser();
$currentApiKey = $this->tokenRepository->findOneBy(array('user' => $this->user));
if ($currentApiKey) {
$this->em->remove($currentApiKey);
$this->em->flush();
}
$this->saveApiKey();
return $this;
}
private function saveApiKey()
{
$token = new Token();
$dateCreated = new \DateTime("now");
$dateExpired = new \DateTime($dateCreated->format("Y/m/d H:i:s") . "+1 day");
$token->setApiKey($this->apiKey);
$token->setDateCreated($dateCreated);
$token->setDateExpired($dateExpired);
$token->setUser($this->user);
$this->em->persist($token);
$this->em->flush();
}
}
但是当我致电$this->saveApiKey()
时,我有一个奇怪的错误:数据库中的用户 password
变空了。
当我调试此问题时,我注意到salt
在password
消失后未重新创建{/ 1}}。
我还尝试删除一对一关系,(当然更新数据库和清除缓存),但即使令牌表也与用户无关,将令牌保存到db。
后,我将password
更改为空
$this->saveApiKey()
未拨打电话时,一切正常。
请帮助我抓住这个奇怪的错误。非常感谢您的帮助!
答案 0 :(得分:0)
<强>解决即可。我的eraseCredentials()
不正确,因此我的密码变为null
。
另请参阅my another question,我已开始更改我的身份验证系统。