Loading skill
Install any skill in seconds. Free to start, no credit card required.
Get Started Free →Buenas prácticas de seguridad en Laravel para autenticación/autorización, validación, CSRF, asignación masiva, subida de archivos, secretos, limitación de velocidad y despliegue seguro.
| Test case | Without → With | Effect | Δ tokens | Δ turns |
|---|---|---|---|---|
| case-02 | ✗→✓ | ▲ Improved | 58% | 0% |
| case-04 | ✗→✓ | ▲ Improved | 78% | 0% |
| case-19 | ✓→✓ | = Same ✓ | 99% | 0% |
| case-03 | ✓→✓ | = Same ✓ | 89% | 0% |
| case-05 | ✓→✓ | = Same ✓ | 75% | 0% |
针对 Laravel 应用程序的全面安全指导,以防范常见漏洞。
VerifyCsrfToken 实现 CSRF,通过 SecurityHeaders 实现安全标头)。auth:sanctum、$this->authorize、策略中间件)。UploadInvoiceRequest)。RateLimiter::for('login'))。URL::temporarySignedRoute + signed 中间件)。APP_DEBUG=falseAPP_KEY 必须设置,并在泄露时轮换SESSION_SECURE_COOKIE=true 和 SESSION_SAME_SITE=lax(对于敏感应用,使用 strict)SESSION_HTTP_ONLY=true 以防止 JavaScript 访问SESSION_SAME_SITE=strict路由保护示例:
phpuse Illuminate\Http\Request; use Illuminate\Support\Facades\Route; Route::middleware('auth:sanctum')->get('/me', function (Request $request) { return $request->user(); });
Hash::make() 哈希密码,切勿存储明文phpuse Illuminate\Support\Facades\Hash; use Illuminate\Validation\Rules\Password; $validated = $request->validate([ 'password' => ['required', 'string', Password::min(12)->letters()->mixedCase()->numbers()->symbols()], ]); $user->update(['password' => Hash::make($validated['password'])]);
php$this->authorize('update', $project);
使用策略中间件进行路由级强制执行:
phpuse Illuminate\Support\Facades\Route; Route::put('/projects/{project}', [ProjectController::class, 'update']) ->middleware(['auth:sanctum', 'can:update,project']);
$fillable 或 $guarded,避免使用 Model::unguard()phpDB::select('select * from users where email = ?', [$email]);
{{ }}){!! !!}VerifyCsrfToken 中间件启用@csrf,并为 SPA 请求发送 XSRF 令牌对于使用 Sanctum 的 SPA 身份验证,确保配置了有状态请求:
php// config/sanctum.php 'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', 'localhost')),
phpfinal class UploadInvoiceRequest extends FormRequest { public function authorize(): bool { return (bool) $this->user()?->can('upload-invoice'); } public function rules(): array { return [ 'invoice' => ['required', 'file', 'mimes:pdf', 'max:5120'], ]; } }
php$path = $request->file('invoice')->store( 'invoices', config('filesystems.private_disk', 'local') // set this to a non-public disk );
throttle 中间件phpuse Illuminate\Cache\RateLimiting\Limit; use Illuminate\Http\Request; use Illuminate\Support\Facades\RateLimiter; RateLimiter::for('login', function (Request $request) { return [ Limit::perMinute(5)->by($request->ip()), Limit::perMinute(5)->by(strtolower((string) $request->input('email'))), ]; });
对静态的敏感列使用加密转换。
phpprotected $casts = [ 'api_token' => 'encrypted', ];
设置标头的中间件示例:
phpuse Illuminate\Http\Request; use Symfony\Component\HttpFoundation\Response; final class SecurityHeaders { public function handle(Request $request, \Closure $next): Response { $response = $next($request); $response->headers->add([ 'Content-Security-Policy' => "default-src 'self'", 'Strict-Transport-Security' => 'max-age=31536000', // add includeSubDomains/preload only when all subdomains are HTTPS 'X-Frame-Options' => 'DENY', 'X-Content-Type-Options' => 'nosniff', 'Referrer-Policy' => 'no-referrer', ]); return $response; } }
config/cors.php 中限制来源php// config/cors.php return [ 'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], 'allowed_origins' => ['https://app.example.com'], 'allowed_headers' => [ 'Content-Type', 'Authorization', 'X-Requested-With', 'X-XSRF-TOKEN', 'X-CSRF-TOKEN', ], 'supports_credentials' => true, ];
phpuse Illuminate\Support\Facades\Log; Log::info('User updated profile', [ 'user_id' => $user->id, 'email' => '[REDACTED]', 'token' => '[REDACTED]', ]);
composer audit使用签名路由生成临时的、防篡改的链接。
phpuse Illuminate\Support\Facades\URL; $url = URL::temporarySignedRoute( 'downloads.invoice', now()->addMinutes(15), ['invoice' => $invoice->id] );
phpuse Illuminate\Support\Facades\Route; Route::get('/invoices/{invoice}/download', [InvoiceController::class, 'download']) ->name('downloads.invoice') ->middleware('signed');
Other measured skills in the registry, with their headline benchmark lift.