0

I am programming an application that uses ReactJs for the front-end in localhost:3001 and Symfony for the back-end localhost:3000, and to enable cross origin communication I use "cors-bundle" in Symfony. Now I want to create a Cookie when a user log in, but it doesn't seem to be created !

Thanks for your help,

This is the code in Symfony the moment a user logs in :

use Symfony\Component\HttpFoundation\Cookie;


$cookie = new Cookie( 'my_cookie', 1, strtotime('tomorrow') );
$res = new Response();
$res->headers->setCookie( $cookie );
return new JsonResponse($res);

This what I also tried :

$res->headers->setCookie(Cookie::create('my_cookie', 1));
return new JsonResponse($res);

3 Answers3

4

What you need is:

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;

class YourClass extends AbstractController {

    public function yourMethod(Request $request) {
        $cookie = new Cookie(
                      "cookie_name_here",                      // Cookie name
                      1,                                       // Cookie content
                      (new DateTime('now'))->modify("+1 day"), // Expiration date
                      "/",                                     // Path
                      "localhost",                             // Domain
                      $request->getScheme() === 'https',       // Secure
                      false,                                   // HttpOnly
                      true,                                    // Raw
                      'Strict'                                 // SameSite policy
                  );
        $res = new JsonResponse();
        $res->headers->setCookie($cookie);
        return $res;
    }
}

Things to note here.

  1. Setting the "Secure" flag will mean this cookie is only transmitted on a HTTPS connection. Do not neglect this in production. You may want to use $request->getScheme() === 'https' as the parameter evaluation.

  2. The "HttpOnly" flag is for security and stops Javascipt and Browser extensions from accessing the cookie. If you're using XHR to make requests (for instance, Axios) and include "withCredentials" then this is ok to set as true and will be sent anyway. If you want to read the value in React then set this to false

MattBoothDev
  • 1,294
  • 2
  • 15
  • 25
0

It should be

$res = new JsonResponse();

$res->headers->setCookie($cookie); Return $res;

Alexander Dimitrov
  • 944
  • 1
  • 6
  • 17
0

I've not experienced any difference in doing this from Symfony 2. This has already been answered here: How to attach cookies to JSON Response in symfony2?

Have you checked your browser's developer tools to see if a cookie is arriving in the response? Specifically look at the Network tab and monitor the headers of the AJAX response.

Adambean
  • 1,096
  • 1
  • 9
  • 18