Giao diện
Laravel Passport
- Giới thiệu
- Cài đặt
- Cấu hình
- Authorization Code Grant
- Authorization Code Grant với PKCE
- Device Authorization Grant
- Password Grant
- Client Credentials Grant
- Personal Access Tokens
- Protecting Routes
- Token Scopes
- SPA Authentication
- Events
- Testing
Nguồn gốc: Bản dịch từ Laravel Passport
Giới thiệu (Introduction)
Laravel Passport cung cấp triển khai OAuth2 server đầy đủ cho ứng dụng Laravel. Passport được xây dựng trên League OAuth2 server.
Passport hay Sanctum?
- Passport: OAuth2 đầy đủ — phù hợp khi cần cấp token cho ứng dụng bên thứ ba
- Sanctum: Đơn giản hơn — phù hợp cho SPA, mobile app, API token cơ bản
Nếu không cần OAuth2 đầy đủ, dùng Sanctum.
Cài đặt (Installation)
bash
composer require laravel/passportbash
php artisan passport:installDeploying Passport
Chạy passport:keys trên server production.
Cấu hình (Configuration)
Token Lifetimes
Cấu hình thời gian sống của access token và refresh token.
Overriding Default Models
Tùy chỉnh Passport models.
Authorization Code Grant
Flow OAuth2 phổ biến nhất cho ứng dụng web.
Managing Clients
Tạo và quản lý OAuth client qua Artisan hoặc API.
Requesting Tokens
Redirect user đến authorization endpoint → nhận authorization code → exchange lấy token.
Refreshing Tokens
Dùng refresh token để lấy access token mới.
Revoking Tokens
Thu hồi token.
Authorization Code Grant với PKCE
Dành cho public client (SPA, mobile) không thể lưu secret an toàn.
Device Authorization Grant
Dành cho thiết bị có input hạn chế (TV, IoT).
Password Grant
Xác thực bằng username/password trực tiếp (first-party apps).
Client Credentials Grant
Xác thực machine-to-machine, không cần user.
Personal Access Tokens
Cho phép user tự tạo API token cho chính mình.
Protecting Routes
Bảo vệ route bằng middleware auth:api.
Token Scopes
Defining Scopes
Định nghĩa scopes giới hạn quyền truy cập API.
Assigning Scopes to Tokens
Gán scope khi request token.
Checking Scopes
Kiểm tra scope trên request/token.
SPA Authentication
Passport hỗ trợ xác thực SPA qua cookie.
Events
Passport dispatch events khi token được tạo/revoke.
Testing
Sử dụng actingAs để fake token trong test.