我在 Symfony2 中的登录和身份验证遇到了一些问题。例外情况是“$user 必须是 UserInterface 实例、实现 __toString 方法的对象或原始字符串。”
调试我的代码我可以注意到我尝试登录我的应用程序的用户可以成功通过身份验证(app/log/dev.log),但凭据 var 为空:
AbstractToken 的用户变量具有数据库中的用户数据。
我继续在 ContextListener->refreshUser 函数中调试,我得到了这些值:
一切都具有 null 值,并且 Symfony\Bridge\Doctrine\Security\User\EntityUserProvider->refreshUser 函数将变量 $refreshedUser 返回为 null,因此当 ContextListener 类上的函数 $token->setUser($refreshedUser) 失败并且抛出异常。
我写下我的 security.yml 和我正在使用的实体:
安全性.yml:
security:
encoders:
Pladuch\BackBundle\Entity\BaseUser:
algorithm: sha512
encode_as_base64: false
iterations: 1
providers:
sga:
entity: { class: 'PladuchBackBundle:Usuario', property: username }
firewalls:
dev:
pattern: ^/(_(profiler|wdt)|css|images|js)/
security: false
sga:
pattern: ^/gestion
anonymous: ~
form_login:
login_path: pladuch_login_sga
check_path: pladuch_login_check
default_target_path: pladuch_sga_index
csrf_provider: form.csrf_provider
provider: sga
logout:
path: pladuch_logout_sga
target: pladuch_login_sga
access_control:
- { path: ^/gestion/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
- { path: ^/gestion, roles: ROLE_ADMIN }
抽象类 BaseUser:
<?php
namespace Pladuch\BackBundle\Entity;
use Symfony\Component\Security\Core\User\AdvancedUserInterface;
abstract class BaseUser implements AdvancedUserInterface, \Serializable
{
protected $id;
protected $salt;
protected $username;
protected $password;
public function __construct()
{
$this->isActive = true;
$this->salt = $this->generateSalt();
}
public function serialize()
{
return serialize(array($this->id, $this->username, $this->password));
}
public function unserialize($serialized)
{
list($this->id, $this->username, $this->password) = unserialize($serialized);
}
public function getRoles()
{
return array('ROLE_ADMIN');
}
public function getPassword()
{
return $this->password;
}
public function setPassword($password)
{
$this->password = $password;
}
public function getUsername()
{
return $this->username;
}
public function eraseCredentials()
{
}
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
public function getSalt()
{
return $this->salt;
}
public function generateSalt()
{
return base_convert(sha1(uniqid(mt_rand(), true)), 16, 36);
}
public function isAccountNonExpired()
{
return true;
}
public function isAccountNonLocked()
{
return true;
}
public function isCredentialsNonExpired()
{
return true;
}
public function isEnabled()
{
return true;
}
}
类乌苏里奥:
<?php
namespace Pladuch\BackBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* Usuario
*
* @ORM\Table(name="usuario",
* uniqueConstraints={
* @ORM\UniqueConstraint(name="username", columns={"username"})
* },
* indexes={@ORM\Index(name="FK_USUARIO_ROL", columns={"rol_id"})})
* @ORM\Entity(repositoryClass="Pladuch\BackBundle\Repository\UsuarioRepository")
*/
class Usuario extends BaseUser
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer", nullable=false)
* @ORM\Id()
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* @var string
*
* @ORM\Column(name="username", type="string", length=255, nullable=false)
*/
protected $username;
/**
* @var string
*
* @ORM\Column(name="password", type="string", length=1024, nullable=false)
*/
protected $password;
/**
* @var string
*
* @ORM\Column(name="salt", type="string", length=1024, nullable=false)
*/
protected $salt;
/**
* @var string
*
* @ORM\Column(name="email", type="string", length=255, nullable=false)
*/
protected $email;
/**
* @var Rol
*
* @ORM\ManyToOne(targetEntity="Rol", inversedBy="id")
* @ORM\JoinColumns({
* @ORM\JoinColumn(name="rol_id", referencedColumnName="id")
* })
*/
protected $rol;
/**
* @var bool
*
* @ORM\Column(name="activo", type="boolean", nullable=true)
*/
protected $activo = true;
/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set username
*
* @param string $username
* @return Usuario
*/
public function setUsername($username)
{
$this->username = $username;
return $this;
}
/**
* Get username
*
* @return string
*/
public function getUsername()
{
return $this->username;
}
/**
* Set password
*
* @param string $password
* @return Usuario
*/
public function setPassword($password)
{
$this->password = $password;
return $this;
}
/**
* Get password
*
* @return string
*/
public function getPassword()
{
return $this->password;
}
/**
* Set salt
*
* @param string $salt
* @return Usuario
*/
public function setSalt($salt)
{
$this->salt = $salt;
return $this;
}
/**
* Get salt
*
* @return string
*/
public function getSalt()
{
return $this->salt;
}
/**
* Set email
*
* @param string $email
* @return Usuario
*/
public function setEmail($email)
{
$this->email = $email;
return $this;
}
/**
* Get email
*
* @return string
*/
public function getEmail()
{
return $this->email;
}
/**
* Set rol
*
* @param Rol $rol
* @return Usuario
*/
public function setRol(Rol $rol = null)
{
$this->rol = $rol;
return $this;
}
/**
* Get rol
*
* @return Rol
*/
public function getRol()
{
return $this->rol;
}
/**
* @return array|\Symfony\Component\Security\Core\Role\Role[]
*/
public function getRoles()
{
return array($this->getRol()->getRol());
}
/**
* Set activo
*
* @param $activo
* @return $this
*/
public function setActivo($activo)
{
$this->activo = $activo;
return $this;
}
/**
* Get activo
*
* @return bool
*/
public function getActivo()
{
return $this->activo;
}
}
我实现三个函数 loadUserByUsername、refreshUser 和 supportsClass 的 UsuarioRepository:
class UsuarioRepository extends EntityRepository implements UserProviderInterface
{
public function loadUserByUsername($username)
{
$q = $this->createQueryBuilder('u')
->where('u.username = :username')
->setParameter('username', $username)
->getQuery();
try {
$user = $q->getSingleResult();
} catch (NoResultException $e) {
$message = sprintf('Unable to find an active Usuario object identified by %s', $username);
throw new UsernameNotFoundException($message, 0, $e);
}
return $user;
}
public function refreshUser(UserInterface $userInterface)
{
$class = get_class($userInterface);
if (! $this->supportsClass($class)) {
throw new UnsupportedUserException(sprintf('Instances of %s are not suppoted', $class));
}
}
public function supportsClass($class)
{
return $this->getEntityName() === $class || is_subclass_of($class, $this->getEntityName());
}
}
感谢您的帮助。
亲切的问候。
PS:我使用的是 Symfony 2.5.6