How to add Laravel Socialite login to SPA that authenticates with Laravel Sanctum

213 Views Asked by At

I have a vue3 app that authenticates to a Laravel backend using Sanctum.

My auth workflow for the Sanctum backend looks like this:

  • Front end makes ajax request to API with user/pass
  • Back end checks user/pass in database
  • Auth::login($user) is called, creating the session
  • API returns response to front-end, which contains the sanctum cookies
  • Front end redirects to protected dashboard

I'm trying to add a Google sign-in via Socialite. The workflow as described in the Socialte docs is this:

  • add button to front-end that redirects to api redirect route:
    public function redirect(): \Symfony\Component\HttpFoundation\RedirectResponse|\Illuminate\Http\RedirectResponse
    {
        return Socialite::driver('google')->redirect();
    }
  • User then is redirected into a Google OAuth screen. They log in.
  • After logging in, the user is then redirected to the callback URL.
    public function callback(Request $request): \Illuminate\Http\RedirectResponse|\Symfony\Component\HttpFoundation\RedirectResponse
    {
        session()->put('state', $request->input('state'));
        $googleUser = Socialite::driver('google')->user();
        
        // business-specific auth logic

        Auth::login($user);
        session()->regenerate();

        // attempt to add cookie manually, does not work
        $cookie = new Cookie(
            session()->getName(),
            session()->getId(),
            config('session.lifetime'),
            '/',
            '.app.local',
            false,
            true,
            false,
            'lax'
        );

        return redirect('http://app.local/dashboard')->withCookie($cookie);
    }

The problem is that this redirect doesn't include the Sanctum cookies. Google redirects to the API back-end, which then redirects back to the front-end. So when the front-end loads, the client does not have the cookies necessary for the ensuing protected back-end requests, and the front-end redirects back to the login screen.

I have tried many things to make this work, but I can't quite figure out a solution here. Creating the cookie manually doesn't seem to work; Chrome won't show the headers on the request. It instead says "Provisional headers are shown".

1

There are 1 best solutions below

0
qotsa42 On BEST ANSWER

This issue is likely caused by having to use an ngrok URL as the redirect value in the config file.

  • API URL: api.app.local
  • SPA URL: spa.app.local
  • Google redirect: api.app.local/auth/callback

Google requires you to use a public URL, so I used an NGROK url as the callback URL. This seems to strip the request of the cookies needed to authenticate with Sanctum, stranding the request without a way to communicate the session ID to the back end.

Pushing to a public test environment fixes the issue.