Search code examples
javascriptphpreactjssymfonyfetch-api

Symfony Session & Fetch


so I'll try to be explicit:

I have a middleware in my symfony's project which is supposed to increment the number of connection attempts in the session variable (RequestStack::getSession()) which works quite well in Postman, the problem being that it does not work with Fetch, the returned session seems empty after "debug". I suspect the PHPSESSID is not stored in my Fetch when the session is created by Symfony

Middleware

public function __construct(JWTEncoderInterface $jwtEncoder, RequestStack $requestStack, ManagerRegistry $doctrine)
    {
        $this->jwtEncoder = $jwtEncoder;
        $this->requestStack = $requestStack;
        $this->session = $this->requestStack->getSession();
        $this->doctrine = $doctrine;
    }

public function onAuthenticationFailure(Request $request, AuthenticationException $exception): JsonResponse
    {
        // debug
        // return new JsonResponse([$this->session->all(), 'error' => true, 'message' => 'Authentication failed'], 401);

        // check if login is restricted
        $this->loginResricted();
        
        // increment attempt in session
        $this->incrementAttempt($request);

        return new JsonResponse(['error' => true, 'message' => 'Authentication failed'], 401);
    }

I tried to debug the session but nothing in output, but I need to keep the user session alive till he is trying to login


Solution

  • So, I found an alternative to my problem if someone is looking for it:

    Two ways:

    • you can store it to your database (more secure I think)
    • or in Symfony's Cache Component

    This is my scheme if you are interested:

    UserAttempt

    {
      "id": int,
      "ip": string,
      "logins": array,
      "delay": int,
      "created_at": datetime,
      "updated_at": datetime
    }
    

    You will be able to track user attempts based on his IP.