laravel開發:如何使用laravel sanctum實現spa身份驗證?
Laravel Sanctum是Laravel的官方包,旨在為SPA(單頁應用程序)和移動應用程序提供簡單、輕量級的API身份驗證。它使用短暫令牌而不是永久憑證,以增強安全性,并提供多種身份驗證驅動程序,包括Cookie、API密鑰和JWT。
在這篇文章中,我們將討論如何使用Laravel Sanctum實現SPA身份驗證。
第一步是安裝Laravel Sanctum。可以在Laravel應用程序中使用composer安裝它:
composer require laravel/sanctum
安裝后,需要運行migrations以創建Sanctum所需的表:
php artisan migrate
接下來,需要打開app/http/Kernel.php文件,并在API中間件組中添加Laravel Sanctum的中間件:
LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class, 'throttle:60,1', IlluminateRoutingMiddlewareSubstituteBindings::class, ],``` 現在,Laravel Sanctum已準備好開始在應用程序中進行SPA身份驗證。 下一步是將Sanctum添加到Vue或React應用程序中。為此,需要在應用程序中安裝axios或其他HTTP客戶端庫,以便與后端通信。建議使用axios來演示下面的示例代碼。 axios需要配置一下:
import axios from ‘axios’
export const HTTP = axios.create({
baseURL: http://localhost:8000/api/,
withCredentials: true,
})
withCredentials選項允許axios將cookie發送到后端,這對于使用Laravel Sanctum進行身份驗證非常重要。 現在,可以在Vue組件或React組件中使用以下代碼來進行身份驗證:
// 登錄
login() {
axios.post('/login', this.credentials) .then(response => { this.getUser() })
},
// 注銷
logout() {
axios.post('/logout') .then(response => { this.$store.commit('logout') })
},
// 獲取用戶信息
getUser() {
axios.get('/user') .then(response => { this.$store.commit('updateUser', response.data) }).catch(error => { console.log(error) })
},
在這個例子中,我們使用axios來向/login和/logout路由發送POST請求,以及向/user路由發送GET請求。這三個路由應該在Laravel應用程序中定義,并使用Laravel Sanctum進行身份驗證。 使用Laravel Sanctum的默認身份驗證驅動程序- cookie-,可以通過以下方式發送令牌:
// Vue中
axios.defaults.headers.common[‘X-csrf-Token’] = document.querySelector(‘meta[name=”csrf-token”]’).getAttribute(‘content’);
// React中
import { setAuthToken } from ‘./axiosConfig’;
axios.defaults.headers.common[‘X-CSRF-TOKEN’] = setAuthToken();
這將在每個請求中設置名為X-CSRF-TOKEN的標頭。此標頭包含一個CSRF令牌,該令牌是在使用Laravel Sanctum時進行身份驗證所必需的。