Laravel Sanctum is a lightweight authentication system for SPAs and mobile, it’s the token based APIs, here is a simple example with Vue.js.
Firstly, initial the project and require sanctum.
1$ composer create-project --prefer-dist laravel/laravel laravel82$ composer require laravel/sanctum3$ php artisan vendor:publish --provider="Laravel\Sanctum\SanctumServiceProvider"4$ php artisan migrate
app/Http/Kernel.php
1'api' => [2 \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,3 'throttle:api',4 \Illuminate\Routing\Middleware\SubstituteBindings::class,5],
Set all of the environment and database, go into the tinker ,and create a user, by default with laravel, the password should be ‘password’.
1\App\Models\User::factory()->create(['email' => 'user@test.com']);
Next, setting stateful domains, it can be any, for this example, I would be to set localhost:8080
for frontend project based on Vue-cli, also you need to set session domain.
1SANCTUM_STATEFUL_DOMAINS=localhost,127.0.0.1,127.0.0.1:8000,::1,localhost:80802SESSION_DOMAIN=localhost
Set cross domain path in cors.php
and credentials
validation is true.
1'paths' => ['api/*', 'login', 'logout', 'sanctum/csrf-cookie'],23'supports_credentials' => true,
Laravel Sanctum is already setuped, move up to vue-cli.
Install vue-cli and router, required axois
and navigate to main.js
set withCredentials
and baseURL
to default, the base url is server endpoint.
1const axios = window.axios = require('axios');23axios.defaults.withCredentials = true;4axios.defaults.baseURL = 'http://localhost:8000';
Next, add a simple login form, here is my example code, and also you need to initialize CSRF protection for the application, finally requesting to login.
1<form action="#" method="POST" @submit.prevent="login">2 <div>3 email: <input type="text" v-model="email">4 </div>5 <div>6 password: <input type="password" v-model="password">7 </div>89 <div>10 <input type="submit">11 </div>12 </form>13<script>1415export default {16 name: 'Home',17 data() {18 return {19 email: null,20 password: null21 }22 },23 methods: {24 login() {25 axios.get('/sanctum/csrf-cookie').then(response => {26 axios.post('/login', {27 email: this.email,28 password: this.password,29 }).then(res => {30 this.$router.push({name: 'Dashboard'});31 })32 });33 }34 }35}36</script>
Modified the default api middleware to auth:sanctum for protected route.
1Route::middleware('auth:sanctum')->get('/user', function (Request $request) {2 return $request->user();3});
Here is my Dashboard.vue
sample code, as you can see, when I login successful, I will retrieve user data and model binding to property.
Finally, I created logout method, just a simple, requesting logout endpoint and redirect to Home.
1<template>2 <div class="home">3 <h1>Dashboard view</h1>4 <h2 v-if="email">{{ email }}</h2>5 <button @click="logout">Logout</button>67 </div>8</template>910<script>11export default {12 name: 'Home',13 data() {14 return {15 email: null16 }17 },18 mounted() {19 axios.get('/api/user')20 .then(res => {21 this.email = res.data.email22 })23 },24 methods: {25 logout() {26 axios.post('logout').then(res => {27 this.$router.push({name: 'Home'})28 })29 }30 }31}32</script>
Laravel Sanctum is really simple and useful token based authentication system for laravel eco system, if you’re using it for mobile authentication you should add HasApiTokens
trait to create token, it’s really ease to use.
Laravel Sanctum – Laravel – The PHP Framework For Web Artisans