我正在使用下面列出的MakerBundle 1.8的功能为Symfony 4应用设置登录身份验证:
php bin/console make:auth
本文介绍了此功能:https://symfony.com/blog/new-in-makerbundle-1-8-instant-user-login-form-commands
我可以查看表单并尝试登录,但是我不知道如何正确添加具有密码和角色的用户。
我尝试通过数据库在角色字段中使用如下字符串创建用户:
{"path":"^/admin","roles":"ROLE_ADMIN"}
(我在security.yml的“ access_control”下发现了JSON)
但是当我尝试以该用户身份登录时,会收到一条消息,提示“无效的凭据”。我怀疑这是因为安全性正在使用加密,而我添加到数据库中的用户是纯文本。
如果您对我如何添加用户以测试通过MakerBundle的make:auth功能添加的安全性有任何建议,请告诉我。
更新:感谢William的回答!这是您提供的固定装置的修改版本,允许我登录。
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManage;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Entity\User;
use Doctrine\Common\Persistence\ObjectManager;
class UserFixtures extends Fixture
{
public function __construct(UserPasswordEncoderInterface $encoder)
{
$this->encoder = $encoder;
}
public function load(ObjectManager $manager)
{
$user = new User();
$user->setEmail("myemail@somedomain.io");
$roles = array("path" => "^/admin", "roles" => "ROLE_ADMIN");
$user->setRoles($roles);
$password = $this->encoder->encodePassword($user, 'pass_1234');
$user->setPassword($password);
$manager->persist($user);
$manager->flush();
}
}
?>
答案 0 :(得分:0)
<?php
namespace App\DataFixtures;
use Doctrine\Bundle\FixturesBundle\Fixture;
use Doctrine\Common\Persistence\ObjectManage;
use Symfony\Component\Security\Core\Encoder\UserPasswordEncoderInterface;
use App\Entity\User;
class UserFixtures extends Fixture
{
public function __construct(UserPasswordEncoderInterface $encoder)
{
$this->encoder = $encoder;
}
public function load(ObjectManager $manager)
{
$numberOfUsers = 10;
for($i = 0; $i < $numberOfUsers; $i++) {
$user = new User();
$user->setUsername(sprintf('test%d', $i));
$user->addRole('ROLE_ADMIN');
$password = $this->encoder->encodePassword($user, 'pass_1234');
$user->setPassword($password);
$manager->persist($user);
}
$manager->flush();
}
}
?>
最后,您执行命令:
php bin/console doctrine:fixtures:load