Search code examples
phplaravelcookieslaravel-socialite

Cookie is removed after gmail login


I'm implementing an online reservation system using Laravel Framework version 5.6 and Laravel Socialite to implement gmail login.

I have a method that checks if user is logged in before reservation, or it puts reserveData and redirectUrl specified by an uniqid in redis and cookie to fetch it after logging in:

public function checkAuthentication(Request $request)
{
    $reserveData = json_decode($request->input('reserveData'), true);
    Session::put('reserveData', $reserveData);

    if (!Auth::check()) {
        $reserveID = uniqid();
        Cookie::queue(Cookie::forget('reserveID'));
        Cookie::queue(Cookie::make('reserveID', $reserveID, 1440));

        $stepData = [
            'redirectUrl' => route('reserve', ['productId' => $reserveData['productId']]),
            'reserveData' => $reserveData
        ];

        Redis::set($reserveID, serialize($stepData));

        return redirect()->route('redirectToGmail');
    }

    return redirect()->route('reserve', ['productId' => $reserveData['productId']]);
}

redirectToGmail:

public function redirectToGmail()
{
    return Socialite::driver('google')->redirect();
}

The problem is, the uniqid doesn't exist in cookie after returning back from gmail only for the first time that user tries to login:

public function login()
{
    $user = Socialite::driver('google')->stateless()->user();
    dd(Cookie::get());
}

Here it is my output of dd(Cookie::get()); after returning back from gmail:

array:4 [▼
    "XSRF-TOKEN" => "DxiHpLSqB8juOkdLSptORyXs2XGggwWuY4tKJDkz"
    "project_session" => "Gy7p3nhUNGF9D34FmWYxyvewb6juiDNSVLXWTDvS"
    "__cfduid" => null
]

Solution

  • Laravel by default sets the domain parameter of Cookie::make() method to current host address, that it contains www. sub domain in it. As you can see it by calling getHost() method:

    request()->getHost(); // returns e.g. www.yourdomain.com
    

    The return url that I had already registered in gmail service was mydomain.com/return/url. I had set the cookie without passing any domain to it, so the default host address was set that it differences with the registered domain in gmail.

    I removed the previous domain (mydomain.com/return/url) from gmail and registered it with www. sub domain (www.mydomain.com/return/url). Also I passed the path and domain arguments to Cookie::make() method and it works like a charm ;) :

    Cookie::queue(Cookie::forget('reserveID', '/', $request->getHost()));
    Cookie::queue(Cookie::make('reserveID', $reserveID, 1440, '/', $request->getHost()));