I have implemented a custom authenticator through the new simple_form functionnality
main:
pattern: ^/
simple_form:
authenticator: custom_authenticator
provider: fos_userbundle
csrf_provider: form.csrf_provider
remember_me:
key: "%secret%"
lifetime: 31536000 # 365 jours
path: /
domain: ~
name: my_remember_cookie
The authenticateToken() method from my Authenticator looks like:
try {
$user = $userProvider->loadUserByUsername($token->getUsername());
} catch (UsernameNotFoundException $e) {
throw new AuthenticationException('Unknown user');
}
if ($user->isLocked() === true) {
throw new AuthenticationException('User locked');
}
if (/* Logic checks */) {
return new UsernamePasswordToken(
$user, null, $providerKey, $user->getRoles()
);
}
I was wondering if, from this point, there is a method to programmatically set the remember me cookie (in my case i want to set it according to the user's role) ?
Edit: I solved it thanks to sebbo, the whole point is to manually set the remember_me parameter in the $request object before passing it to the rememberMe service.
My final code:
/**
* onAuthenticationSuccess
*
* @param Request $request
* @param TokenInterface $token
* @return Response
*/
public function onAuthenticationSuccess(Request $request, TokenInterface $token) {
$url = $this->container->get("session")->get('_security.main.target_path') ? $this->container->get("session")->get('_security.main.target_path') : $this->container->get("router")->generate('home');
$response = $request->isXmlHttpRequest() ?
new JsonResponse(array(
"success" => true,
"url" => $url
)) : new RedirectResponse($url);
// Relevant part
$rememberMeService = $this->container->get("EDE.security.service.remember_me");
$request->attributes->set($rememberMeService->getRememberMeParameter(), 'true'/*set to other than 'yes'|'true'|'on'|'1' to force to don't set cookie*/);
$rememberMeService->loginSuccess($request, $response, $token);
return $response;
}
The service alias:
<service id="EDE.security.service.remember_me" alias="security.authentication.rememberme.services.simplehash.main"></service>
The manual request parameter assignment seems a little bit dirty, but it works.
To set the remember me cookie programmatically we are using the following code in our application:
// setting the remember me token
$this->container->get('our_company.security.service.remember_me')->loginSuccess(
$request,
$response,
$this->container->get('security.context')->getToken()
);
Consider that the service definition for our_company.security.service.remember_me
is only an alias for the Symfony2 remember me service. We had to create this alias to make the remember me service public.
This is the service definition:
<service id="our_company.security.service.remember_me" alias="security.authentication.rememberme.services.simplehash.main"/>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With