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:
Make sure you have a Laravel project set up. If not, create a new Laravel project:
bashcomposer create-project --prefer-dist laravel/laravel your-project-name
cd your-project-name
Install Laravel Sanctum:
bashcomposer require laravel/sanctum
php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"
php artisan migrate
Add the \Laravel\Sanctum\HasApiTokens
trait to your User
model:
phpuse Laravel\Sanctum\HasApiTokens;
class User extends Authenticatable
{
use HasApiTokens, Notifiable;
// ...
}
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,
Define the API routes in routes/api.php
. You can use the Sanctum middleware to protect your routes:
phpuse Illuminate\Support\Facades\Route;
Route::middleware(['auth:sanctum'])->group(function () {
// Your authenticated routes here
});
Create a middleware for Sanctum to handle CORS headers and authenticate SPA requests. Create a new middleware:
bashphp artisan make:middleware EnsureFrontendRequestsAreStateful
Update the middleware (app/Http/Middleware/EnsureFrontendRequestsAreStateful.php
):
phpnamespace 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');
}
}
Register the middleware in app/Http/Kernel.php
:
phpprotected $middlewareGroups = [
// ...
'api' => [
// ...
\App\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
],
];
Install the Axios library for making HTTP requests:
bashnpm install axios
Create a service file for your API calls (e.g., api.js
):
javascriptimport axios from 'axios';
const apiClient = axios.create({
baseURL: 'http://your-laravel-api-url',
withCredentials: true,
});
export default apiClient;
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;
}
},
};
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.