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

Lesson 12: Security Best Practices

CSRF protection, XSS prevention. SQL injection, mass assignment protection. Rate limiting, encryption. CORS configuration. HTTPS enforcement, security headers. OWASP for Laravel.

💻 Programming — Lesson 12 Lesson 12: Security Best Practices

Laravel: From Basics to Advanced

Part 3: Authentication & Authorization

xdev.asia

1. CSRF & XSS Prevention

{{-- 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 Injection & Mass Assignment

// 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. Encryption & Hashing

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. Security Headers & 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. Rate Limiting

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

Next article: Queues & Jobs.