How to authenticate/authorize anonymous user for a limited time? How to authenticate/authorize anonymous user for a limited time? symfony symfony

How to authenticate/authorize anonymous user for a limited time?


Create a kernel.request listener. This way you can act, before anything is executed, and whole application is oblivious to the fact that the user can be logged out any minute.

Call a "service" which will validate the token. If the token is not valid, clear authentication status and override the request. For instance, redirect the user to a "you need to pay again" page.

This way you don't need to modify any code, execute any voters and so on, your whole application can be protected.

As for the authentication itself, go for a custom guard, where you can fully control how the authentication process will work.


You can authenticate a dummy user for 15 minutes using the following action:

use Symfony\Component\Security\Core\Authentication\Token\UsernamePasswordToken;use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;public function indexAction(Request $request){    $em = $this->getDoctrine()->getManager();    /**     * confirm that the user indeed owns      * phone number related to the invoice (code verification)     */    //create a user for this task only and fetch it    $user = $em->getRepository(User::class)->find(1);    //firewall name used for authentication in security.yml    $firewall = "main_secured_area";    $token = new UsernamePasswordToken($user, null, $firewall, $user->getRoles());    $this->get('security.token_storage')->setToken($token);    $this->get('session')->set("_security_$firewall", serialize($token));    //$lifetime takes number of seconds to define session timeout 15min = 900sec    $this->container->get('session')->migrate($destroy = false, $lifetime = 900);    //fire the login event manually    $event = new InteractiveLoginEvent($request, $token);    $this->get("event_dispatcher")->dispatch("security.interactive_login", $event);    return $this->render('default/index.html.twig');}