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

レッスン 12: セキュリティのベスト プラクティス

CSRF 保護、XSS 防止。 SQL インジェクション、一括割り当て保護。レート制限、暗号化。 CORS 構成。 HTTPS の強制、セキュリティ ヘッダー。 Laravel の OWASP。

💻 プログラミング — レッスン 12 レッスン 12: セキュリティのベスト プラクティス

Laravel: 基本から上級まで

パート 3: 認証と認可

xdev.asia

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');

次の記事: キューとジョブ。