Chuyển đến nội dung chính

第 12 課:安全最佳實踐

CSRF防護,XSS防護。 SQL注入、批次賦值保護。速率限制、加密。 CORS 配置。 HTTPS 強制執行、安全標頭。 Laravel 的 OWASP。

💻 程式設計 — 第 12 課 第 12 課:安全最佳實踐

Laravel:從基礎到高級

第 3 部分:身份驗證和授權

亞洲開發網

1. CSRF和XSS預防

{{-- CSRF token tự động --}}
<form method="POST">
    @csrf
    ...
</form>

{{-- XSS — Blade auto-escapes --}}
{{ $userInput }}           {{-- Đã escape --}}
{!! $trustedHtml !!}       {{-- Raw — chỉ dùng với dữ liệu tin cậy --}}

2. SQL注入&批量賦值

// Eloquent & Query Builder tự động parameterize
Product::where('name', $input)->get(); // ✅ Safe

// Raw query — dùng bindings
DB::select('SELECT * FROM products WHERE name = ?', [$input]); // ✅

// Mass assignment protection
class Product extends Model
{
    protected $fillable = ['name', 'price', 'description'];
    // HOẶC
    protected $guarded = ['id', 'is_admin'];
}

3. 加密和雜湊

use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\Hash;

// Encryption (two-way)
$encrypted = Crypt::encryptString('sensitive data');
$decrypted = Crypt::decryptString($encrypted);

// Hashing (one-way — cho passwords)
$hashed = Hash::make('password');
Hash::check('password', $hashed); // true

4. 安全標頭和 HTTPS

// Middleware
class SecurityHeaders
{
    public function handle($request, Closure $next)
    {
        $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('Strict-Transport-Security', 'max-age=31536000; includeSubDomains');
        return $response;
    }
}

// Force HTTPS
// AppServiceProvider
if (app()->isProduction()) {
    URL::forceScheme('https');
}

5. 速率限制

RateLimiter::for('login', function (Request $request) {
    return [
        Limit::perMinute(5)->by($request->ip()),
        Limit::perMinute(10)->by($request->input('email')),
    ];
});

Route::post('/login', [AuthController::class, 'login'])->middleware('throttle:login');

下一篇: 佇列和作業。