Chuyển đến nội dung
Skillpedia
Bảo mật280k · #200

laravel-security

Skill này làm gì

Agent này giúp ứng dụng Laravel của bạn an toàn hơn. Nó kiểm tra các thiết lập quan trọng, như bảo vệ chống các tấn công phổ biến (XSS, CSRF), quản lý người dùng và cách ứng dụng giao tiếp qua internet.

Khi nào nên dùng

  • ✓Khi thiết lập bảo mật cho một ứng dụng Laravel mới.
  • ✓Khi xem xét một ứng dụng Laravel hiện có để tìm lỗ hổng bảo mật.
  • ✓Trước khi đưa ứng dụng Laravel của bạn vào hoạt động chính thức (production).

Liên kết skill

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-security/SKILL.md

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-security/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để đảm bảo ứng dụng Laravel của tôi được bảo vệ khỏi tấn công XSS?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó phân tích các thiết lập của ứng dụng Laravel, như xác thực, phân quyền và các thiết lập chống tấn công phổ biến. Nó đề xuất hoặc kiểm tra xem các thiết lập này có đúng không để ngăn ngừa sự cố.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

Laravel Security Best Practices

Comprehensive security guidelines for Laravel applications to protect against common vulnerabilities.

When to Activate

  • Setting up Laravel authentication and authorization (Sanctum, Passport, Jetstream, Breeze)
  • Implementing user roles, permissions, and policies
  • Configuring production security settings and environment variables
  • Reviewing Laravel applications for security vulnerabilities
  • Deploying Laravel applications to production
  • Writing secure Eloquent queries and migrations

Production Configuration

Essential Production Settings

// config/app.php
'env' => env('APP_ENV', 'production'),
'debug' => (bool) env('APP_DEBUG', false), // CRITICAL: Never true in production
'key' => env('APP_KEY'), // Must be set: php artisan key:generate

// config/session.php
'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax',

// Verify APP_KEY is set at boot
// bootstrap/app.php or a service provider
if (empty(config('app.key'))) {
    throw new RuntimeException('APP_KEY is not set. Run: php artisan key:generate');
}

Environment File Security

# NEVER commit .env to version control
# .gitignore already includes .env by default

# Use .env.example with placeholders instead
DB_PASSWORD=
APP_KEY=
SANCTUM_TOKEN_PREFIX=

# Validate required variables at boot
// In AppServiceProvider::boot()
$requiredKeys = ['app.key', 'database.connections.mysql.database', 'database.connections.mysql.username'];
foreach ($requiredKeys as $key) {
    if (empty(config($key))) {
        throw new RuntimeException("Missing required config key: {$key}");
    }
}

HTTPS Enforcement

// AppServiceProvider::boot() or middleware
if (app()->environment('production')) {
    URL::forceScheme('https');
    request()->server->set('HTTPS', 'on');
}

// config/app.php for trusted proxies (load balancers)
// Use specific IP ranges — * trusts all, allowing X-Forwarded-* spoofing
// 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'],

// Force HTTPS in production via middleware
// 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);
}

Authentication

Sanctum (API Token Authentication)

// 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, // Token expiration in minutes (null = never)
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),

// Issuing tokens with abilities
$token = $user->createToken('api-token', ['read', 'write'])->plainTextToken;

// Validate abilities on routes
Route::middleware('auth:sanctum')->group(function () {
    Route::get('/orders', function () {
        // User must have 'read' ability
        abort_unless(Auth::user()->tokenCan('read'), 403);
        // ...
    })->middleware('abilities:read');

    Route::post('/orders', function () {
        // User must have 'write' ability
        abort_unless(Auth::user()->tokenCan('write'), 403);
        // ...
    })->middleware('abilities:write');
});

Password Security

// config/hashing.php
// Default is bcrypt. Argon2id is stronger.
'bcrypt' => [
    'rounds' => env('BCRYPT_ROUNDS', 12), // Increase for stronger hashing
],

'argon' => [
    'memory' => 65536,
    'threads' => 4,
    'time' => 4,
],

// Password validation in RegisterRequest
public function rules(): array
{
    return [
        'password' => [
            'required',
            'confirmed',
            Password::min(12)
                ->letters()
                ->mixedCase()
                ->numbers()
                ->symbols()
                ->uncompromised(), // Checks haveibeenpwned
        ],
    ];
}

// Rate limit login attempts
// App\Http\Controllers\Auth\AuthenticatedSessionController
protected function authenticated(Request $request, $user)
{
    if ($user->wasRecentlyLockedOut()) {
        // Notify user of suspicious login
        $user->notify(new SuspiciousLoginNotification($request->ip()));
    }
}

Session Management

// config/session.php

…
Câu hỏi thường gặp

CSRF và XSS là gì?

Đây là các loại tấn công web. CSRF cố lừa người dùng thực hiện hành động không mong muốn. XSS chèn mã script độc hại vào website của bạn.

Xác thực và phân quyền là gì?

Xác thực là kiểm tra xem bạn là ai (đăng nhập bằng tài khoản và mật khẩu). Phân quyền là kiểm tra những gì bạn được phép làm sau khi đã đăng nhập.

Tại sao cần cấu hình 'APP_KEY'?

APP_KEY dùng để mã hóa dữ liệu nhạy cảm trong ứng dụng. Nếu nó không được thiết lập hoặc kẻ tấn công biết được, dữ liệu của bạn có thể bị xâm phạm.

Chi tiết

Mô tả gốc của tác giả

Laravel security best practices — authentication, authorization, Eloquent safety, CSRF, XSS prevention, API security, and secure deployment configurations. Use when reviewing Laravel auth, Eloquent safety, CSRF, XSS, API security, or deployment configuration.

repo: affaan-m/ECC

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#200
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự