laravel-auth
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseLaravel Authentication & Authorization
Laravel 身份认证与授权
Agent Workflow (MANDATORY)
Agent 工作流(必须执行)
Before ANY implementation, use to spawn 3 agents:
TeamCreate- fuse-ai-pilot:explore-codebase - Check existing auth setup, guards, policies
- fuse-ai-pilot:research-expert - Verify latest Laravel 12 auth docs via Context7
- mcp__context7__query-docs - Query specific patterns (Sanctum, Passport, etc.)
After implementation, run fuse-ai-pilot:sniper for validation.
在进行任何实现之前,使用生成3个Agent:
TeamCreate- fuse-ai-pilot:explore-codebase - 检查现有的认证设置、守卫(guards)、策略(policies)
- fuse-ai-pilot:research-expert - 通过Context7验证Laravel 12最新的认证文档
- mcp__context7__query-docs - 查询特定模式(如Sanctum、Passport等)
实现完成后,运行fuse-ai-pilot:sniper进行验证。
Overview
概述
Laravel provides a complete authentication and authorization ecosystem. Choose based on your needs:
| Package | Best For | Complexity |
|---|---|---|
| Starter Kits | New projects, quick setup | Low |
| Sanctum | API tokens, SPA auth | Low |
| Fortify | Custom UI, headless backend | Medium |
| Passport | OAuth2 server, third-party access | High |
| Socialite | Social login (Google, GitHub) | Low |
Laravel提供了完整的身份认证与授权生态系统。可根据需求选择合适的工具:
| 包 | 适用场景 | 复杂度 |
|---|---|---|
| Starter Kits | 新项目、快速搭建 | 低 |
| Sanctum | API令牌、SPA认证 | 低 |
| Fortify | 自定义UI、无头后端 | 中 |
| Passport | OAuth2服务器、第三方访问 | 高 |
| Socialite | 社交登录(Google、GitHub) | 低 |
Critical Rules
重要规则
- Use policies for model authorization - Not inline checks
if - Always hash passwords - or
Hash::make()cast'hashed' - Regenerate session after login - Prevents fixation attacks
- Use HTTPS in production - Required for secure cookies
- Define token abilities - Principle of least privilege
- 使用策略(policies)进行模型授权 - 不要使用内联判断
if - 始终对密码进行哈希处理 - 使用或
Hash::make()类型转换'hashed' - 登录后重新生成会话 - 防止会话固定攻击
- 生产环境使用HTTPS - 安全Cookie的必要条件
- 定义令牌权限(abilities) - 遵循最小权限原则
Architecture
架构
app/
├── Http/
│ ├── Controllers/
│ │ └── Auth/ ← Auth controllers (if manual)
│ └── Middleware/
│ └── Authenticate.php ← Redirects unauthenticated
├── Models/
│ └── User.php ← HasApiTokens trait (Sanctum)
├── Policies/ ← Authorization policies
│ └── PostPolicy.php
├── Providers/
│ └── AppServiceProvider.php ← Gate definitions
└── Actions/
└── Fortify/ ← Fortify actions (if used)
├── CreateNewUser.php
└── ResetUserPassword.php
config/
├── auth.php ← Guards & providers
├── sanctum.php ← API token config
└── fortify.php ← Fortify featuresapp/
├── Http/
│ ├── Controllers/
│ │ └── Auth/ ← 认证控制器(手动实现时)
│ └── Middleware/
│ └── Authenticate.php ← 重定向未认证用户
├── Models/
│ └── User.php ← 引入HasApiTokens trait(Sanctum)
├── Policies/ ← 授权策略
│ └── PostPolicy.php
├── Providers/
│ └── AppServiceProvider.php ← 门限(Gate)定义
└── Actions/
└── Fortify/ ← Fortify动作(使用时)
├── CreateNewUser.php
└── ResetUserPassword.php
config/
├── auth.php ← 守卫(Guards)与提供者(Providers)配置
├── sanctum.php ← API令牌配置
└── fortify.php ← Fortify功能配置FuseCore Integration
FuseCore 集成
When working in a FuseCore project, authentication follows the modular structure:
FuseCore/
├── Core/ # Infrastructure (priority 0)
│ └── App/Contracts/
│ └── AuthServiceInterface.php ← Auth contract
│
├── User/ # Auth module (existing)
│ ├── App/
│ │ ├── Models/User.php ← HasApiTokens trait
│ │ ├── Http/
│ │ │ ├── Controllers/
│ │ │ │ ├── AuthController.php
│ │ │ │ └── TokenController.php
│ │ │ ├── Requests/
│ │ │ │ ├── LoginRequest.php
│ │ │ │ └── RegisterRequest.php
│ │ │ └── Resources/UserResource.php
│ │ ├── Policies/UserPolicy.php
│ │ └── Services/AuthService.php
│ ├── Config/
│ │ └── sanctum.php ← Sanctum config (module-level)
│ ├── Database/Migrations/
│ ├── Routes/api.php ← Auth routes
│ └── module.json # dependencies: []
│
└── {YourModule}/ # Depends on User module
├── App/Policies/ ← Module-specific policies
└── module.json # dependencies: ["User"]在FuseCore项目中,身份认证遵循模块化结构:
FuseCore/
├── Core/ # 基础设施(优先级0)
│ └── App/Contracts/
│ └── AuthServiceInterface.php ← 认证契约
│
├── User/ # 认证模块(已存在)
│ ├── App/
│ │ ├── Models/User.php ← 引入HasApiTokens trait
│ │ ├── Http/
│ │ │ ├── Controllers/
│ │ │ │ ├── AuthController.php
│ │ │ │ └── TokenController.php
│ │ │ ├── Requests/
│ │ │ │ ├── LoginRequest.php
│ │ │ │ └── RegisterRequest.php
│ │ │ └── Resources/UserResource.php
│ │ ├── Policies/UserPolicy.php
│ │ └── Services/AuthService.php
│ ├── Config/
│ │ └── sanctum.php ← Sanctum模块级配置
│ ├── Database/Migrations/
│ ├── Routes/api.php ← 认证路由
│ └── module.json # 依赖项: []
│
└── {YourModule}/ # 依赖User模块
├── App/Policies/ ← 模块专属策略
└── module.json # 依赖项: ["User"]FuseCore Auth Checklist
FuseCore 认证检查清单
- Auth code in module
/FuseCore/User/ - Policies in module's
/App/Policies/ - Auth routes in
/FuseCore/User/Routes/api.php - Sanctum config in
/FuseCore/User/Config/sanctum.php - Declare dependency in other modules'
"User"module.json - Use middleware in module routes
auth:sanctum
- 认证代码位于模块中
/FuseCore/User/ - 策略位于模块的目录下
/App/Policies/ - 认证路由位于
/FuseCore/User/Routes/api.php - Sanctum配置位于
/FuseCore/User/Config/sanctum.php - 在其他模块的中声明
module.json依赖"User" - 在模块路由中使用中间件
auth:sanctum
Cross-Module Authorization
跨模块授权
php
// In FuseCore/{Module}/Routes/api.php
Route::middleware(['api', 'auth:sanctum'])->group(function () {
Route::apiResource('posts', PostController::class);
});
// In FuseCore/{Module}/App/Http/Controllers/PostController.php
public function update(UpdatePostRequest $request, Post $post)
{
$this->authorize('update', $post); // Uses PostPolicy
// ...
}→ See fusecore skill for complete module patterns.
php
// 在FuseCore/{Module}/Routes/api.php中
Route::middleware(['api', 'auth:sanctum'])->group(function () {
Route::apiResource('posts', PostController::class);
});
// 在FuseCore/{Module}/App/Http/Controllers/PostController.php中
public function update(UpdatePostRequest $request, Post $post)
{
$this->authorize('update', $post); // 使用PostPolicy
// ...
}→ 查看fusecore skill获取完整的模块模式。
Decision Guide
决策指南
Authentication Method
认证方法选择
Need auth scaffolding? → Starter Kit
├── Yes → Use React/Vue/Livewire starter kit
└── No → Building custom frontend?
├── Yes → Use Fortify (headless)
└── No → API only?
├── Yes → Sanctum (tokens)
└── No → Session-based需要认证脚手架? → Starter Kit
├── 是 → 使用React/Vue/Livewire Starter Kit
└── 否 → 是否构建自定义前端?
├── 是 → 使用Fortify(无头模式)
└── 否 → 是否仅API服务?
├── 是 → Sanctum(令牌)
└── 否 → 基于会话的认证Token Type
令牌类型选择
Third-party apps need access? → Passport (OAuth2)
├── No → Mobile app?
│ ├── Yes → Sanctum API tokens
│ └── No → SPA on same domain?
│ ├── Yes → Sanctum SPA auth (cookies)
│ └── No → Sanctum API tokens第三方应用需要访问权限? → Passport(OAuth2)
├── 否 → 是否为移动应用?
│ ├── 是 → Sanctum API令牌
│ └── 否 → 是否为同域名下的SPA?
│ ├── 是 → Sanctum SPA认证(Cookie)
│ └── 否 → Sanctum API令牌Key Concepts
核心概念
| Concept | Description | Reference |
|---|---|---|
| Guards | Define HOW users authenticate (session, token) | authentication.md |
| Providers | Define WHERE users are retrieved from (database) | authentication.md |
| Gates | Closure-based authorization for simple checks | authorization.md |
| Policies | Class-based authorization tied to models | authorization.md |
| Abilities | Token permissions (Sanctum/Passport scopes) | sanctum.md |
| 概念 | 描述 | 参考文档 |
|---|---|---|
| Guards(守卫) | 定义用户的认证方式(会话、令牌) | authentication.md |
| Providers(提供者) | 定义用户数据的获取来源(数据库) | authentication.md |
| Gates(门限) | 基于闭包的授权方式,适用于简单检查 | authorization.md |
| Policies(策略) | 基于类的授权方式,与模型绑定 | authorization.md |
| Abilities(权限) | 令牌的权限范围(Sanctum/Passport的作用域) | sanctum.md |
Reference Guide
参考指南
Concepts (WHY & Architecture)
概念类(原理与架构)
| Topic | Reference | When to Consult |
|---|---|---|
| Authentication | authentication.md | Guards, providers, login flow |
| Authorization | authorization.md | Gates vs policies, access control |
| Sanctum | sanctum.md | API tokens, SPA authentication |
| Passport | passport.md | OAuth2 server, third-party access |
| Fortify | fortify.md | Headless auth, 2FA |
| Socialite | socialite.md | Social login providers |
| Starter Kits | starter-kits.md | Auth scaffolding |
| Email Verification | verification.md | MustVerifyEmail, verified middleware |
| Password Reset | passwords.md | Forgot password flow |
| Session | session.md | Session drivers, flash data |
| CSRF | csrf.md | Form protection, AJAX tokens |
| Encryption | encryption.md | Data encryption (not passwords) |
| Hashing | hashing.md | Password hashing |
| 主题 | 参考文档 | 适用场景 |
|---|---|---|
| 身份认证 | authentication.md | 守卫、提供者、登录流程 |
| 授权 | authorization.md | Gates与Policies对比、访问控制 |
| Sanctum | sanctum.md | API令牌、SPA认证 |
| Passport | passport.md | OAuth2服务器、第三方访问 |
| Fortify | fortify.md | 无头认证、双因素认证(2FA) |
| Socialite | socialite.md | 社交登录提供商 |
| Starter Kits | starter-kits.md | 认证脚手架 |
| 邮箱验证 | verification.md | MustVerifyEmail、verified中间件 |
| 密码重置 | passwords.md | 忘记密码流程 |
| 会话管理 | session.md | 会话驱动、闪存数据 |
| CSRF防护 | csrf.md | 表单防护、AJAX令牌 |
| 加密 | encryption.md | 数据加密(非密码) |
| 哈希处理 | hashing.md | 密码哈希 |
Templates (Complete Code)
模板类(完整代码)
| Template | When to Use |
|---|---|
| LoginController.php.md | Manual authentication controllers |
| GatesAndPolicies.php.md | Gates and policy examples |
| PostPolicy.php.md | Complete policy class with before filter |
| sanctum-setup.md | Sanctum configuration + testing |
| PassportSetup.php.md | OAuth2 server setup |
| FortifySetup.php.md | Fortify configuration + 2FA |
| SocialiteController.php.md | Social login + testing |
| PasswordResetController.php.md | Password reset flow |
| 模板 | 适用场景 |
|---|---|
| LoginController.php.md | 手动实现认证控制器 |
| GatesAndPolicies.php.md | Gates与Policies示例 |
| PostPolicy.php.md | 带前置过滤器的完整策略类 |
| sanctum-setup.md | Sanctum配置与测试 |
| PassportSetup.php.md | OAuth2服务器搭建 |
| FortifySetup.php.md | Fortify配置与双因素认证 |
| SocialiteController.php.md | 社交登录与测试 |
| PasswordResetController.php.md | 密码重置流程 |
Best Practices
最佳实践
DO
建议遵循
- Use starter kits for new projects
- Define policies for all models
- Set token expiration
- Rate limit login attempts
- Use middleware for sensitive actions
verified - Prune expired tokens regularly
- 新项目使用Starter Kits
- 为所有模型定义策略
- 设置令牌过期时间
- 限制登录尝试频率
- 对敏感操作使用中间件
verified - 定期清理过期令牌
DON'T
避免操作
- Store plain text passwords
- Skip session regeneration on login
- Use Passport when Sanctum suffices
- Forget to prune expired tokens
- Ignore HTTPS in production
- Put authorization logic in controllers
- 存储明文密码
- 登录时跳过会话重新生成
- 在Sanctum足够满足需求时使用Passport
- 忘记清理过期令牌
- 生产环境忽略HTTPS
- 将授权逻辑放在控制器中