Symfony2: “Remember me” tries to authenticate by username instad of email

泪湿孤枕 提交于 2019-11-29 16:51:12

You can extend the default remember me service class and override the onLoginSuccess method so it uses the email instead of the username.

  • Service to be extended: security.authentication.rememberme.services.simplehash.class
  • Class: Symfony\Component\Security\Http\RememberMe\TokenBasedRememberMeServices
  • Method: onLoginSuccess

Or you can return the e-mail on the getUsername() function and change the name of your real username field like "nickname"..

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

When you implement the UserInterface, the comment on UserInterface.php say

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

Yes it is "bad" but less verbose. The real problem is this damn function name. Symfony2 should change it..

user3232946

In my case I have just modify the "rememberme" cookie and replace the username by the email like this:

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();
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!