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:
composer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
EnsureFrontendRequestsAreStateful
middleware to the api middleware group within app/Http/Kernel.php
sanctum.php
config file under stateful
using the SANCTUM_STATEFUL_DOMAINS
environment variablecors.php
config file and set support_credentials
to true
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