>我有一个针对数据库的用户身份验证应用程序。我使用的属性是电子邮件:
providers:
administrators:
entity:
class: CorabMainBundle:User
property: email
身份验证效果很好!但是我在让记住我功能工作时遇到了巨大的问题。几个小时后,我想我找到了问题,但我不知道如何解决它......
Symfony2似乎尝试使用用户名而不是电子邮件进行身份验证,以防记住我。
dev.log 说:
[2013-10-21 23:49:19] security.DEBUG: Remember-me cookie detected. [] []
[2013-10-21 23:49:19] doctrine.DEBUG: SELECT t0.id AS id1, t0.username AS username2, t0.salt AS salt3, t0.password AS password4, t0.email AS email5, t0.is_active AS is_active6, t0.organisation AS organisation7 FROM User t0 WHERE t0.email = ? LIMIT 1 ["roger"] []
[2013-10-21 23:49:19] security.INFO: User for remember-me cookie not found. [] []
[2013-10-21 23:49:19] security.DEBUG: Clearing remember-me cookie "REMEMBERME" [] []
第 2 行是不行的,因为它不应该是 roger 而是电子邮件地址。这就是 cookie 被删除的原因。
如何告诉symfony2使用电子邮件作为"记住我"身份验证的属性?
感谢您的帮助!
您可以扩展默认的"记住我"服务类并重写 onLoginSuccess 方法,使其使用电子邮件而不是用户名。
- 要扩展的服务:security.authentication.rememberme.services.simplehash.class
- 类: Symfony''Component''Security''Http''RememberMe''TokenBasedRememberMeServices
- 方法:登录成功
或者
你可以在getUsername()函数上返回电子邮件,并更改你真实用户名字段的名称,如"昵称"。
public function getUsername()
{
return $this->email;
}
当你实现用户界面时,用户界面上的注释.php说
/**
* Returns the username used to authenticate the user.
*
* @return string The username
*/
public function getUsername();
是的,它很"糟糕",但不那么冗长。真正的问题是这个该死的函数名称。Symfony2应该改变它。
就我而言,我只是修改了"记住我"cookie,并通过电子邮件替换用户名,如下所示:
if(userJustLogin) {
// decode cookie
$request = $this->getRequest();
$cookies = $request->cookies->all();
$cookieParts = explode(':', base64_decode($cookies["REMEMBERME"]));
// replace username by email and update hash
list($class, $username, $expires, $hash) = $cookieParts;
$cookieParts[1] = base64_encode($user->getMail());
$cookieParts[3] = hash_hmac('sha256', $class.$user->getMail().$expires.$user->getPassword(), 'YourSecretTokenFromParameters.yml');
// reencode cookie
$cookies["REMEMBERME"] = base64_encode(implode(':', $cookieParts));
$cookie = new Cookie('REMEMBERME', $cookies["REMEMBERME"], $expires);
// send new cookie
$response = new Response();
$response->headers->setCookie($cookie);
$response->send();
}