Laravel Sanctum SPA API Authentication: Part 1
Learn how to set up Laravel Sanctum authenticate single page applications (SPAs) that need to communicate with a Laravel powered API.
Join the DZone community and get the full member experience.
Join For FreeLaravel Sanctum is a lightweight package to help make authentication in single-page or native mobile applications as easy as possible. Where before you had to choose between using the web middleware with sessions or an external package like Tymon's jwt-auth, you can now use Sanctum to accomplish both stateful and token-based authentication.
Installing Laravel Sanctum
First, let's actually install the package using Composer:
composer require laravel/sanctum
Then, we'll have to publish the migration files (and run the migration) with the following commands:
xxxxxxxxxx
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
The last part of Sanctum's installation requires us modifying the app\Http\Kernel.php
file to include a middleware that will inject Laravel's session cookie into our app's frontend. This is what will ultimately enable us to pass and retrieve data as an authenticated user:
xxxxxxxxxx
'api' => [
EnsureFrontendRequestsAreStateful::class,
'throttle:60,1'
]
CORS & Cookies
You should ensure that your application's CORS configuration is returning the Access-Control-Allow-Credentials
header with a value of True
by setting the supports_credentials
option within your application's cors
configuration file to true
.
In addition, you should enable the withCredentials
option on your global axios
instance. Typically, this should be performed in your resources/js/bootstrap.js
file:
xxxxxxxxxx
axios.defaults.withCredentials = true;
Authenticating
To authenticate your SPA, your SPA's login page should first make a request to the /sanctum/csrf-cookie
route to initialize CSRF protection for the application:
xxxxxxxxxx
axios.get('/sanctum/csrf-cookie').then(response => {
// Login...
});
During this request Laravel will set an XSRF-TOKEN
cookie containing the current CSRF token. This token should then be passed in an X-XSRF-TOKEN
header on subsequent requests, which libraries like Axios and the Angular HttpClient will do automatically for you.
Protecting Routes
To protect routes so that all incoming requests must be authenticated, you should attach the sanctum
authentication guard to your API routes within your routes/api.php
file.
xxxxxxxxxx
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
return $request->user();
});
Published at DZone with permission of Razet Jain. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments