我今天一直在尝试使用 Symfony2 创建一个登录表单,用户可以使用他们的电子邮件地址和密码登录。我遇到了很多问题,最后意识到只有在我的实体类中有一个$username
属性时它才会起作用。AdminUser
我已经尝试在可能的情况下使用电子邮件而不是用户名,所以有人可以解释为什么$username
需要或我哪里出错了?另外,在我的login.html.twig
文件中,我仍在使用,_username
而不是_email
这有什么不同?我的代码如下(我删除了一些不适用的 getter 和 setter):
管理员用户实体:
namespace XXX\WebsiteBundle\Entity;
use Symfony\Component\Security\Core\User\UserInterface;
use Doctrine\ORM\Mapping as ORM;
/**
* AdminUser
*
* @ORM\Table(name="admin_user",indexes={@ORM\Index(name="indexes", columns={"deleted"})})
* @ORM\Entity
* @ORM\HasLifecycleCallbacks()
*/
class AdminUser implements UserInterface
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="name", type="string", length=45)
*/
private $name;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=45, unique=true)
*/
private $email;
/**
* @var string
*
* @ORM\Column(name="salt", type="string", length=255)
*/
private $salt;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=255)
*/
private $password;
/**
* @var integer
*
* @ORM\Column(name="enabled", type="integer", options={"default" = 0})
*/
private $enabled;
/**
* @var string[] $roles
*
* @ORM\Column(name="roles", type="array")
*/
private $roles = array();
private $username;
/**
* Gets the username.
*
* @return string The username.
*/
public function getUsername()
{
return $this->email;
}
/**
* Erases the user credentials.
*/
public function eraseCredentials()
{
}
/**
* Returns the roles granted to the user.
*
* <code>
* public function getRoles()
* {
* return array('ROLE_USER');
* }
* </code>
*
* Alternatively, the roles might be stored on a ``roles`` property,
* and populated in any number of different ways when the user object
* is created.
*
* @return Role[] The user roles
*/
public function getRoles() {
return $this -> roles;
}
/**
* Set the roles of the user
*
* @var string[] $roles
*
* @return \XXX\WebsiteBundle\Entity\User this
*/
public function setRoles(array $roles) {
$this -> roles = $roles;
return $this;
}
}
我的security.yml
文件是:
jms_security_extra:secure_all_services:假表达式:真
security:
encoders:
XXX\WebsiteBundle\Entity\AdminUser: sha512
role_hierarchy:
ROLE_ADMIN: ROLE_USER
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
providers:
main_provider:
entity: { class: XXX\WebsiteBundle\Entity\AdminUser, property: email }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
admin_firewall:
pattern: ^/admin.*
anonymous: ~
form_login:
login_path: /admin/login
check_path: /admin/login_check
access_control:
- { path: ^/admin/login.*, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/admin.*, roles: ROLE_ADMIN }