Laravel 安全最佳实践 是做什么的?
针对 Laravel 应用程序的全面安全指南,以防范常见漏洞。
何时激活
- 设置 Laravel 身份验证和授权(Sanctum、Passport、Jetstream、Breeze)
- 实现用户角色、权限和策略
- 配置生产环境安全设置和环境变量
- 审查 Laravel 应用程序的安全漏洞
- 将 Laravel 应用程序部署到生产环境
- 编写安全的 Eloquent 查询和迁移
生产环境配置
基本生产设置
// config/app.php
'env' => env('APP_ENV', 'production'),
'debug' => (bool) env('APP_DEBUG', false), // 关键:生产环境永远不要设为 true
'key' => env('APP_KEY'), // 必须设置:php artisan key:generate
// config/session.php
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',
// 启动时验证 APP_KEY 已设置
// bootstrap/app.php 或服务提供者
if (empty(config('app.key'))) {
throw new RuntimeException('APP_KEY 未设置。请运行:php artisan key:generate');
}
环境文件安全
# 永远不要将 .env 提交到版本控制
# .gitignore 默认已包含 .env
# 改用带有占位符的 .env.example
DB_PASSWORD=
APP_KEY=
SANCTUM_TOKEN_PREFIX=
# 启动时验证必需的变量
// 在 AppServiceProvider::boot() 中
$requiredKeys = ['app.key', 'database.connections.mysql.database', 'database.connections.mysql.username'];
foreach ($requiredKeys as $key) {
if (empty(config($key))) {
throw new RuntimeException("缺少必需的配置键:{$key}");
}
}
HTTPS 强制
// AppServiceProvider::boot() 或中间件
if (app()->environment('production')) {
URL::forceScheme('https');
request()->server->set('HTTPS', 'on');
}
// config/app.php 中的受信代理(负载均衡器)
// 使用特定的 IP 范围 — * 信任所有 IP,允许 X-Forwarded-* 欺骗
// AWS:'10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16'
'trusted_proxies' => ['10.0.0.0/8', '172.16.0.0/12'],
// 通过中间件在生产环境中强制 HTTPS
// app/Http/Middleware/ForceHttps.php
public function handle($request, Closure $next)
{
if (!$request->secure() && app()->environment('production')) {
return redirect()->secure($request->getRequestUri());
}
return $next($request);
}
身份验证
Sanctum(API 令牌认证)
// config/sanctum.php
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
env('APP_URL') ? ',' . parse_url(env('APP_URL'), PHP_URL_HOST) : ''
)));
'expiration' => 60 * 24, // 令牌过期时间(分钟),null 表示永不过期
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
// 颁发具有权限的令牌
$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;
// 在路由上验证权限
Route::middleware('auth:sanctum')->group(function () {
Route::get('/orders', function () {
// 用户必须具有 'read' 权限
abort_unless(Auth::user()->tokenCan('read'), 403);
// ...
})->middleware('abilities:read');
Route::post('/orders', function () {
// 用户必须具有 'write' 权限
abort_unless(Auth::user()->tokenCan('write'), 403);
// ...
})->middleware('abilities:write');
});
密码安全
// config/hashing.php
// 默认为 bcrypt。Argon2id 更安全。
'bcrypt' => [
'rounds' => env('BCRYPT_ROUNDS', 12), // 增加以提高哈希强度
],
'argon' => [
'memory' => 65536,
'threads' => 4,
'time' => 4,
],
// RegisterRequest 中的密码验证
public function rules(): array
{
return [
'password' => [
'required',
'confirmed',
Password::min(12)
->letters()
->mixedCase()
->numbers()
->symbols()
->uncompromised(), // 检查 haveibeenpwned
],
];
}
// 限制登录尝试次数
// App\Http\Controllers\Auth\AuthenticatedSessionController
protected function authenticated(Request $request, $user)
{
if ($user->wasRecentlyLockedOut()) {
// 通知用户可疑登录
$user->notify(new SuspiciousLoginNotification($request->ip()));
}
}
会话管理
// config/session.php
'driver' => env('SESSION_DRIVER', 'database'), // database/redis > file
'lifetime' => env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
'encrypt' => env('SESSION_ENCRYPT', false),
// 登录时重新生成会话
// App\Http\Controllers\Auth\AuthenticatedSessionController
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate(); // 关键:防止会话固定攻击
return redirect()->intended(RouteServiceProvider::HOME);
}
// 注销时使会话失效
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
授权
Gates
// App\Providers\AuthServiceProvider
use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
public function boot(): void
{
Gate::define('update-post', function (User $user, Post $post): bool {
return $user->id === $post->user_id;
});
Gate::define('publish-post', function (User $user): bool {
return $user->role === 'editor' || $user->role === 'admin';
});
// 使用 before() 实现超级管理员覆盖
Gate::before(function (User $user, string $ability): ?bool {
if ($user->role === 'super-admin') {
return true; // 授予所有能力
}
return null; // 回退到正常检查
});
}
// 在控制器中使用
public function update(Request $request, Post $post): RedirectResponse
{
Gate::authorize('update-post', $post);
// 或者:$this->authorize('update-post', $post);
// 或者:abort_unless(Auth::user()->can('update-post', $post), 403);
// ...
}
策略
// App\Policies\PostPolicy
class PostPolicy
{
use HandlesAuthorization;
public function viewAny(?User $user): bool
{
return true; // 公开列表
}
public function view(?User $user, Post $post): bool
{
return $post->is_published || ($user && $user->id === $post->user_id);
}
public function create(User $user): bool
{
return $user->hasVerifiedEmail(); // 必须先验证邮箱
}
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
public function delete(User $user, Post $post): bool
{
return $user->id === $post->user_id && $post->created_at->diffInDays(now()) <= 30;
}
public function restore(User $user, Post $post): bool
{
return $user->role === 'admin';
}
public function forceDelete(User $user, Post $post): bool
{
return $user->role === 'super-admin';
}
}
// 在 AuthServiceProvider 中注册
protected $policies = [
Post::class => PostPolicy::class,
];
// 控制器使用
public function show(Post $post): View
{
$this->authorize('view', $post);
return view('posts.show', compact('post'));
}
// Blade 中使用
@can('update', $post)
<a href="{{ route('posts.edit', $post) }}">编辑</a>
@endcan
@cannot('update', $post)
<span>您无法编辑此帖子</span>
@endcannot
中间件授权
// 在路由中使用中间件
Route::put('/posts/{post}', [PostController::class, 'update'])
->middleware('can:update,post');
Route::get('/posts/create', [PostController::class, 'create'])
->middleware('can:create,App\Models\Post');
// 自定义授权中间件
// app/Http/Middleware/CheckRole.php
class CheckRole
{
public function handle(Request $request, Closure $next, string $role): mixed
{
if (!$request->user() || $request->user()->role !== $role) {
abort(403, '未授权。此区域需要角色:' . $role);
}
return $next($request);
}
}
// 在 Kernel 中注册
protected $routeMiddleware = [
'role' => \App\Http\Middleware\CheckRole::class,
];
// 路由使用
Route::middleware(['auth', 'role:admin'])->group(function () {
Route::get('/admin', [AdminController::class, 'index']);
});
Eloquent 安全
批量赋值保护
// 错误:$guarded = [] 允许所有字段批量赋值
// 永远不要在生产环境中使用 $guarded = []
// 正确:白名单 fillable 属性
final class User extends Authenticatable
{
protected $fillable = [
'name',
'email',
'phone',
'avatar',
];
// 永远不要将 'role', 'is_admin', 'is_verified' 添加到此处
}
// 正确:在请求中显式控制哪些字段可以被填充
public function store(StoreUserRequest $request): RedirectResponse
{
$user = User::create($request->safe()->only([
'name', 'email', 'phone', 'avatar'
]));
// $request->safe() 仅使用经过验证的数据
// 没有验证规则时,$request->only() 本身不安全
}
// 错误:直接使用请求数据创建用户
User::create($request->all()); // 容易受到批量赋值攻击!
// 更好:使用 DTO 进行创建
$user = User::create($request->validated()); // 仅验证过的字段
SQL 注入预防
// 正确:Eloquent 自动参数化查询
User::where('email', $userInput)->first();
User::whereRaw('email = ?', [$userInput])->first();
// 正确:查询构建器也参数化
DB::table('users')->where('email', $userInput)->first();
DB::select('SELECT * FROM users WHERE email = ?', [$userInput]);
// 错误:原始字符串插值
DB::select("SELECT * FROM users WHERE email = '{$userInput}'"); // 易受攻击!
User::whereRaw("email = '{$userInput}'")->first(); // 易受攻击!
// 错误:whereRaw/orderByRaw 使用未转义的输入
User::orderByRaw($userInput); // 易受攻击!
User::groupByRaw($userInput); // 易受攻击!
// 错误:DB::statement 使用字符串拼接
DB::statement("INSERT INTO users (email) VALUES ('{$userInput}')"); // 易受攻击!
属性类型转换
final class User extends Authenticatable
{
protected $casts = [
'email_verified_at' => 'datetime',
'is_admin' => 'boolean', // 转换为布尔值可防止字符串注入
'settings' => 'array', // 自动 json_encode/json_decode
'metadata' => 'encrypted:array', // Laravel 11+ 加密转换
'password' => 'hashed', // Laravel 10+ 设置时自动哈希
];
}
模型安全
final class User extends Authenticatable
{
// 从 JSON/API 响应中隐藏敏感属性
protected $hidden = [
'password',
'remember_token',
'two_factor_secret',
'two_factor_recovery_codes',
];
// 仅附加安全的计算属性
protected $appends = ['full_name']; // 安全
// 永远不要附加敏感的计算数据
}
final class Post extends Model
{
// 全局作用域以过滤软删除记录
use SoftDeletes;
// 通过限制惰性加载防止 N+1(可选严格模式)
// AppServiceProvider::boot()
// Model::preventLazyLoading(!app()->isProduction());
}
CSRF 保护
默认保护
// Laravel CSRF 默认通过 VerifyCsrfToken 中间件启用
// app/Http/Kernel.php (protected $middlewareGroups['web'])
// 所有 POST/PUT/PATCH/DELETE 表单必须包含 @csrf
<form method="POST" action="/posts">
@csrf
<input type="text" name="title">
<button type="submit">创建</button>
</form>
排除路由(谨慎操作)
// app/Http/Middleware/VerifyCsrfToken.php
class VerifyCsrfToken extends Middleware
{
// 仅排除有外部 CSRF 保护的路由(webhook 等)
protected $except = [
'stripe/*', // Stripe webhook 使用自己的签名验证
// 避免通配符 'api/*' — 有状态的 Sanctum 路由需要 CSRF。
// 仅排除特定的无状态 webhook/端点路由。
];
}
使用 JavaScript 的 CSRF
<meta name="csrf-token" content="{{ csrf_token() }}">
<script>
// Axios 示例(Laravel 自带 Axios)
axios.defaults.headers.common['X-CSRF-TOKEN'] = document.querySelector(
'meta[name="csrf-token"]'
).getAttribute('content');
// Fetch 示例
fetch('/posts', {
method: 'POST',
headers: {
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
</script>
XSS 预防
Blade 模板安全
{{-- 安全:由 Blade 自动转义 --}}
{{ $userInput }}
{{-- 危险:原始输出 — 永远不要与用户输入一起使用 --}}
{!! $userInput !!}
{{-- 安全:仅将 {!! !!} 用于您控制的受信任内容 --}}
{!! $trustedHtmlFromYourServer !!}
{{-- 正确:使用特定的转义指令 --}}
@js($data) {{-- 为 JavaScript JSON 编码 --}}
@json($data) {{-- 在模板中 JSON 编码 --}}
{{-- 错误:在原始 HTML 中直接使用用户输入 --}}
<div>{!! $user->bio !!}</div> {{-- 如果用户提供 bio,则易受攻击 --}}
安全 HTML 处理
// 当必须允许某些 HTML 时,使用白名单方法
use HTMLPurifier; // 需要:composer require ezyang/htmlpurifier
public function sanitizeHtml(string $dirty): string
{
$config = \HTMLPurifier_Config::createDefault();
$config->set('HTML.Allowed', 'p,b,i,a[href],ul,ol,li,br');
$config->set('URI.AllowedSchemes', ['http', 'https', 'mailto']);
$purifier = new \HTMLPurifier($config);
return $purifier->purify($dirty);
}
// 在 blade 中:
<div>{!! $sanitizedHtml !!}</div> {{-- 使用经过清理的内容 --}}
// 或者使用 Laravel 的 e() 辅助函数
<div>{{ e($rawContent) }}</div> {{-- 双重转义以防止 XSS --}}
API 安全
速率限制
// app/Http/Kernel.php
'api' => [
'throttle:api',
\Illuminate\Routing\Middleware\SubstituteBindings::class,
],
// 自定义速率限制
// AppServiceProvider::boot()
RateLimiter::for('api', function (Request $request) {
return Limit::perMinute(60)->by($request->user()?->id ?: $request->ip());
});
// 登录尝试限制
RateLimiter::for('login', function (Request $request) {
return Limit::perMinute(5)->by($request->input('email') . '|' . $request->ip());
});
// 在控制器中使用
public function store(StoreOrderRequest $request): JsonResponse
{
$this->middleware('throttle:30,1'); // 1 分钟内 30 次尝试
// ...
}
API 响应安全标头
// 中间件:app/Http/Middleware/SecurityHeaders.php
public function handle(Request $request, Closure $next): mixed
{
$response = $next($request);
$response->headers->set('X-Content-Type-Options', 'nosniff');
$response->headers->set('X-Frame-Options', 'DENY');
$response->headers->set('X-XSS-Protection', '1; mode=block');
$response->headers->set('Referrer-Policy', 'strict-origin-when-cross-origin');
$response->headers->set('Permissions-Policy', 'camera=(), microphone=(), geolocation=()');
// 设置严格的 CSP(如果尚未通过 meta 标签设置)
$response->headers->set('Content-Security-Policy', "default-src 'self'");
// 设置 HSTS(仅在 HTTPS 上)
if (app()->environment('production')) {
$response->headers->set('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
}
return $response;
}
// 在 Kernel 中注册
protected $middlewareGroups = [
'web' => [
// ...
\App\Http\Middleware\SecurityHeaders::class,
],
];
CORS 配置
// config/cors.php
return [
'paths' => ['api/*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'], // 或限定为 ['GET', 'POST', 'PUT', 'DELETE']
'allowed_origins' => env('CORS_ALLOWED_ORIGINS')
? explode(',', env('CORS_ALLOWED_ORIGINS'))
: ['http://localhost:3000'], // 生产环境中限制
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => [],
'max_age' => 0,
'supports_credentials' => true, // 用于 Sanctum SPA 身份验证
];
安全部署
部署前清单
# 1. 生成应用程序密钥
php artisan key:generate --force
# 2. 验证生产环境配置
php artisan config:cache
php artisan route:cache
php artisan view:cache
php artisan event:cache
# 3. 确保调试模式已关闭
# 验证 APP_DEBUG=false 在 .env 中
# 4. 移除所有开发/调试工具
composer install --no-dev --optimize-autoloader
# 5. 设置文件权限
# storage/ 和 bootstrap/cache/ 应对 Web 服务器用户可写
# 其他文件应为只读
find . -type f -exec chmod 644 {} \;
find . -type d -exec chmod 755 {} \;
chmod -R 775 storage bootstrap/cache
# 6. 启用数据库 SSL
# 如果数据库支持,在 database.connections.mysql 中配置 ssl
# 7. 检查依赖项的已知漏洞
# 使用 Enlightn 或 composer audit
composer audit
环境变量验证
// app/Providers/AppServiceProvider.php
public function boot(): void
{
// 确保关键变量已设置
$criticalVariables = [
'APP_KEY',
'APP_ENV',
'DB_HOST',
'DB_DATABASE',
'DB_USERNAME',
'DB_PASSWORD',
];
foreach ($criticalVariables as $variable) {
if (empty(env($variable))) {
throw new RuntimeException("缺少关键环境变量:{$variable}");
}
}
// 验证 APP_ENV 是否为 'production'
if (!app()->environment('production') && app()->runningInConsole() === false) {
// 根据需要在开发/预发布环境中执行额外检查
}
}
监控与日志
安全事件日志
// 监听安全事件(AuthServiceProvider::boot())
Event::listen(function (Login $event) {
Log::info('用户登录', [
'user_id' => $event->user->id,
'email' => $event->user->email,
'ip' => request()->ip(),
'user_agent' => request()->userAgent(),
'timestamp' => now(),
]);
});
Event::listen(function (Failed $event) {
Log::warning('登录失败', [
'email' => $event->credentials['email'],
'ip' => request()->ip(),
'user_agent' => request()->userAgent(),
'timestamp' => now(),
]);
// 多次失败后通知管理员
$attempts = Cache::get('login_attempts_' . request()->ip(), 0);
Cache::put('login_attempts_' . request()->ip(), $attempts + 1, 3600);
if ($attempts >= 10) {
// 发送警报(电子邮件、Slack 等)
Log::critical('来自 IP 的多次登录失败:' . request()->ip());
}
});
// 自定义安全日志
ActivityLog::log('user_deleted', ['user_id' => $user->id, 'deleted_by' => Auth::id()]);
错误报告安全
// config/app.php
// 生产环境中禁用调试
'debug' => (bool) env('APP_DEBUG', false),
// config/logging.php
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => ['daily', 'slack'],
'ignore_exceptions' => false,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'error'),
'days' => 14,
],
],
// 使用 Monolog 防止敏感数据泄露
// bootstrap/app.php
$app->configureMonologUsing(function ($monolog) {
$monolog->pushProcessor(function ($record) {
// 从日志中移除敏感字段
$sensitiveFields = ['password', 'token', 'secret', 'credit_card'];
array_walk_recursive($record, function (&$value, $key) use ($sensitiveFields) {
foreach ($sensitiveFields as $field) {
if (stripos($key, $field) !== false) {
$value = '*** 已移除 ***';
}
}
});
return $record;
});
});
常用命令
# 应用程序密钥
php artisan key:generate
php artisan key:generate --show
# 安全工具
composer audit # 检查依赖项漏洞
composer require --dev enlightn/enlightn # Laravel 安全检查工具
php artisan enlightn # 运行安全审计
# 优化
php artisan config:cache # 缓存配置(安全!)
php artisan route:cache # 缓存路由
php artisan view:cache # 缓存 Blade 视图
# 验证
php artisan config:check # 验证配置语法(Laravel 9+)
php artisan route:list # 列出所有路由
# 调试(仅限开发环境)
php artisan make:policy PostPolicy # 创建新策略
php artisan make:middleware ForceHttps # 创建中间件