Skip to content

Laravel Sanctum ​

Nguồn gốc: Bản dịch từ Laravel Sanctum

Giới thiệu (Introduction) ​

Laravel Sanctum cung cấp hệ thống authentication nhẹ cho SPA (single page applications), mobile apps và API token đơn giản. Sanctum cho phép mỗi user tạo nhiều API token cho tài khoản.

Cách hoạt động ​

API Tokens ​

Sanctum tạo API token (không dùng OAuth). Token được lưu trong bảng personal_access_tokens. Kiểm tra token qua header Authorization: Bearer <token>.

SPA Authentication ​

Sanctum sử dụng cookie-based session authentication — cách tiếp cận an toàn hơn token cho SPA cùng domain. Sử dụng middleware EnsureFrontendRequestsAreStateful.

Cài đặt (Installation) ​

Sanctum đã được cài sẵn trong Laravel. Nếu chưa:

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

API Token Authentication ​

Issuing API Tokens ​

php
$token = $user->createToken('token-name');

return $token->plainTextToken;

Token Abilities ​

Gán quyền cho token (tương tự scopes):

php
$token = $user->createToken('token-name', ['server:update']);

Kiểm tra:

php
if ($user->tokenCan('server:update')) {
    // ...
}

Protecting Routes ​

php
Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

Revoking Tokens ​

php
// Thu hồi tất cả token
$user->tokens()->delete();

// Thu hồi token hiện tại
$request->user()->currentAccessToken()->delete();

Token Expiration ​

Cấu hình thời gian hết hạn token trong config/sanctum.php.

SPA Authentication ​

Sanctum hỗ trợ xác thực SPA (Vue, React, Next.js...) cùng domain qua cookie session.

Cấu hình ​

Cấu hình SANCTUM_STATEFUL_DOMAINS trong .env.

CORS & Cookies ​

Cấu hình CORS cho phép credentials.

Mobile Application Authentication ​

Quy trình tương tự API token — issue token khi login, đính kèm trong header Authorization.

Testing ​

php
Sanctum::actingAs(
    User::factory()->create(),
    ['*']
);