I have started working on the font-end part of the Gamification project which will be SPA powered by React & Apollo GraphQL Client, but before building any of the UI components, I had to figure out the authentication. I decided to use Laravel Sanctum mainly because it's simpler to set up than Passport and I don't need the oAuth currently.

I hit some challenges while setting Laravel Sanctum up, but it actually turned out to be simpler than I thought. There are plenty of tutorials out there on how to configure Laravel sanctum with SPAs but I have not seen one that explains how to set it up with GraphQL client. So here are the steps I took to set this up with my app:

  1. Installed Sanctum: composer require laravel/sanctum
  2. Published config file & migrations: php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
  3. Ran migrations: php artisan migrate
  4. Since I use sanctum to authenticate the SPA I added the EnsureFrontendRequestsAreStateful middleware to the api middleware group within app/Http/Kernel.php
  5. Because my SPA is on the same repository & obviously on the same domain for now, I won't be needing the token based authentication from Sanctum, but instead it will use Laravel's built-in cookie based session authentication. You can read more about it here
  6. Added the domain that my SPA will be making requests from in sanctum.php config file under stateful using the SANCTUM_STATEFUL_DOMAINS environment variable
  7. Updated cors.php config file and set support_credentials to true
  8. Finally, set up the ApolloClient configuration:
const client = new ApolloClient(
   {
       uri: "/graphql",
       headers: {
           "X-CSRF-TOKEN": document.querySelector(`meta[name="csrf-token"]`).content
       },
       credentials: "same-origin",
   }
);

Note that I am using X-CSRF-TOKEN because my SPA is on the same repository as the back-end so I have access to the csrf-token that's set in the meta tag of my app.blade.php. Therefore, I am able to just use that instead of making a request to /sanctum/csrf-cookie to initialize the CSRF cookie & passing X-XSRF-TOKEN. Later down the road I may change this, but for now this does the job.

I will create another post about actually authenticating the user & keeping the user authenticated on SPA while navigating pages or refreshing.

Get notified as soon as new content is published