LogoNavigate back to the homepage

Create an API authentication with Laravel Sanctum

Yish
October 20th, 2020 · 1 min read

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 laravel8
2$ composer require laravel/sanctum
3$ 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:8080
2SESSION_DOMAIN=localhost

Set cross domain path in cors.php and credentials validation is true.

1'paths' => ['api/*', 'login', 'logout', 'sanctum/csrf-cookie'],
2
3'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');
2
3axios.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>
8
9 <div>
10 <input type="submit">
11 </div>
12 </form>
13<script>
14
15export default {
16 name: 'Home',
17 data() {
18 return {
19 email: null,
20 password: null
21 }
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>
6
7 </div>
8</template>
9
10<script>
11export default {
12 name: 'Home',
13 data() {
14 return {
15 email: null
16 }
17 },
18 mounted() {
19 axios.get('/api/user')
20 .then(res => {
21 this.email = res.data.email
22 })
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

Sanctum 认证 |《Laravel 8 中文文档 8.x》| Laravel China 社区

More articles from Yish

阿布都中東料理Abdu Arabian Cuisine

今天拜訪了位於公館的阿布都中東料理,這是我第一次嘗試中東料理,整體來說相當滿意,食物非常好吃。

October 17th, 2020 · 1 min read

How to migrate ‘with’ and ‘whereHas’ in Laravel?

It needs to think about this, for my situation, I need to query when audits table has any data, but the result requiring with it, so how to do this?

October 15th, 2020 · 1 min read
© 2019–2020 Yish
Link to $https://twitter.com/yishlaiLink to $https://github.com/Mombuyish