Log in system and stay logged in

I am trying to implement a single website access token using Symfony2.

Authentication itself works fine, but only for the start page. On the next loaded page, the user will no longer be logged in.

Relevant Code:

$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $event = new InteractiveLoginEvent($request, $token); $this->get("event_dispatcher")->dispatch(SecurityEvents::INTERACTIVE_LOGIN, $event); $this->get("security.context")->setToken($token); return $this->redirect($this->generateUrl('sonata_user_profile_show')); 

First page (without redirecting):

Initial page - logged in

Second page:

Second page - Not logged in anymore

+7
source share
1 answer

For user login, only the following code is required.

 $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles()); $this->get("security.context")->setToken($token); return $this->redirect($this->generateUrl('sonata_user_profile_show')); 

What this means is to set UserPasswordToken in a security context. This token (as well as the user) will be serialized and placed into the session. On the next page, the token will be unesterized from the session, and the updated user will also be updated.

The user user in FOSUserBundle makes this update using the identifier of the unserialized user.

In addition, Doctrine2 in some cases uses proxy classes as entity classes instead of the original entity class. This proxy class overwrites the getId () function of an object with a complex, complex implementation with lazy loading.

This together can lead to the fact that when you put the Doctrine2 proxy object in the UserPasswordToken, the "getId ()" of the serialized and then uncertified proxy object will not return the original identifier. When this happens, the user cannot be updated by the user-provider, and the token will become invalid.

The fix for this is to create a user user that overwrites "refreshUser ()" by updating using the username (or other unique property).

 //... class UserProvider extends FOSUserProvider { /** * {@inheritDoc} */ public function refreshUser(SecurityUserInterface $user) { if (!$user instanceof User) { throw new UnsupportedUserException(sprintf('Expected an instance of User, but got "%s".', get_class($user))); } if (null === $reloadedUser = $this->userManager->findUserBy(array('username' => $user->getUsername()))) { throw new UsernameNotFoundException(sprintf('User with username "%s" could not be reloaded.', $user->getUsername())); } return $reloadedUser; } } 
+6
source

All Articles