How to integrate Laravel Sanctum for SPA authentication with Vue.js



Image not found!!

Integrating Laravel Sanctum with a Vue.js Single Page Application (SPA) for authentication involves several steps. Laravel Sanctum is a simple web authentication package for Laravel that provides a simple way to authenticate single-page applications (SPAs) with Laravel backends. Here's a step-by-step guide on how to set up authentication using Laravel Sanctum with Vue.js:

1. Install Laravel Sanctum

Make sure you have a Laravel project set up. If not, create a new Laravel project:

bash
composer create-project --prefer-dist laravel/laravel your-project-name cd your-project-name

Install Laravel Sanctum:

bash
composer require laravel/sanctum php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider" php artisan migrate

Add the \Laravel\Sanctum\HasApiTokens trait to your User model:

php
use Laravel\Sanctum\HasApiTokens; class User extends Authenticatable { use HasApiTokens, Notifiable; // ... }

2. Configure Laravel Sanctum

Update your config/cors.php file to allow requests from your Vue.js application:

php
'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://your-vue-app-url'], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true,

3. Set up API Routes

Define the API routes in routes/api.php. You can use the Sanctum middleware to protect your routes:

php
use Illuminate\Support\Facades\Route; Route::middleware(['auth:sanctum'])->group(function () { // Your authenticated routes here });

4. Create a Sanctum Middleware for SPA

Create a middleware for Sanctum to handle CORS headers and authenticate SPA requests. Create a new middleware:

bash
php artisan make:middleware EnsureFrontendRequestsAreStateful

Update the middleware (app/Http/Middleware/EnsureFrontendRequestsAreStateful.php):

php
namespace App\Http\Middleware; use Closure; use Illuminate\Http\Request; class EnsureFrontendRequestsAreStateful { public function handle(Request $request, Closure $next) { return $next($request) ->header('Access-Control-Allow-Origin', config('app.frontend_url')) ->header('Access-Control-Allow-Credentials', 'true'); } }

5. Update Kernel

Register the middleware in app/Http/Kernel.php:

php
protected $middlewareGroups = [ // ... 'api' => [ // ... \App\Http\Middleware\EnsureFrontendRequestsAreStateful::class, ], ];

6. Set up Sanctum in Vue.js

Install the Axios library for making HTTP requests:

bash
npm install axios

Create a service file for your API calls (e.g., api.js):

javascript
import axios from 'axios'; const apiClient = axios.create({ baseURL: 'http://your-laravel-api-url', withCredentials: true, }); export default apiClient;

7. Implement Authentication in Vue.js

Create authentication methods in your Vue.js components or Vuex store using the Axios instance:

javascript
// Example login method in a Vuex store import apiClient from '@/services/api'; const actions = { async login({ commit }, credentials) { try { const response = await apiClient.post('/login', credentials); commit('SET_USER', response.data); } catch (error) { console.error('Login error:', error); throw error; } }, };

8. Test Authentication

Test the authentication by making requests to your protected API routes from your Vue.js application.

Remember to adjust the URLs and configurations based on your actual project structure and requirements. This is a basic setup, and you might need to make additional adjustments based on your specific use case.