1

我有一个针对数据库进行用户身份验证的应用程序。我使用的属性是电子邮件:

    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 使用电子邮件作为属性来记住我的身份验证?

谢谢您的帮助!

4

3 回答 3

6

您可以扩展默认的记住我服务类并覆盖 onLoginSuccess 方法,以便它使用电子邮件而不是用户名。

  • 待扩展服务:security.authentication.rememberme.services.simplehash.class
  • 类:Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices
  • 方法:onLoginSuccess
于 2013-12-12T17:45:04.350 回答
3

或者您可以在 getUsername() 函数上返回电子邮件并更改您的真实用户名字段的名称,例如“昵称”..

public function getUsername()
{
    return $this->email;
}

当您实现UserInterface时, UserInterface.php上的注释说

/**
 * Returns the username used to authenticate the user.
 *
 * @return string The username
 */
public function getUsername();

是的,它是“坏的”,但不那么冗长。真正的问题是这个该死的函数名。Symfony2应该改变它..

于 2014-05-29T22:54:50.823 回答
1

就我而言,我刚刚修改了“rememberme”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();
}
于 2016-11-17T19:01:26.093 回答