Security Best Practices

Interview Questions: CSRF, XSS, SQL Injection, and Policies

Q1: How does Laravel protect against CSRF attacks?

Mechanism: Laravel automatically generates a CSRF "token" for each active user session. This token is verified by the VerifyCsrfToken middleware for all POST, PUT, PATCH, and DELETE requests.

Usage: You must include @csrf in your Blade forms.

Q2: How do you prevent SQL Injection in Laravel?

Eloquent/Query Builder: Laravel uses PDO parameter binding by default. This means inputs are never injected directly into the query string but are sent separately to the database driver.

Risk: Raw queries (DB::raw()) are the only place where you are vulnerable if you manually concatenate strings instead of using bindings.

Q3: What are Gates and Policies?

Gates: Closure-based authorization checks. Good for simple, unrelated actions (e.g., Gate::allows('access-admin')).

Policies: Classes that organize authorization logic around a specific model (e.g., PostPolicy with methods like view, create, update).

Q4: What is Mass Assignment Vulnerability and how do you prevent it?

Vulnerability: Occurs when a user passes unexpected HTTP parameters that modify database columns you didn't intend to expose (e.g., passing is_admin=1 in a registration form).

Prevention: Laravel models are protected by default. You must explicitly define which attributes are mass-assignable using $fillable or which are restricted using $guarded.

class User extends Model {
    // Only these can be filled via create() or update()
    protected $fillable = ['name', 'email', 'password'];
    
    // OR: Everything except these can be filled
    // protected $guarded = ['id', 'is_admin'];
}

Q5: How does Blade protect against XSS (Cross-Site Scripting)?

Escaping: By default, Blade's {{ $variable }} syntax automatically runs PHP's htmlspecialchars function, converting special characters to HTML entities. This prevents malicious scripts from executing.

Raw Output: If you explicitly need to render HTML (e.g., from a CMS), you use {!! $variable !!}. This should only be used with trusted content or content that has been sanitized (e.g., using HTML Purifier).

Q6: What are Signed URLs and when would you use them?

Definition: URLs that contain a cryptographic signature hash appended to the query string. Laravel verifies that the URL has not been modified since it was created.

Use Cases:

  • Email Verification: Links sent to users to verify their email address.
  • Unsubscribe Links: Allowing a user to unsubscribe without logging in.
  • Temporary Access: Granting access to a specific resource for a limited time (using temporarySignedRoute).

Q7: What is the difference between Hashing and Encryption in Laravel?

Hashing (Hash::make): One-way transformation. You cannot retrieve the original value. Used for passwords. Laravel uses Bcrypt or Argon2.

Encryption (Crypt::encryptString): Two-way transformation. You can decrypt the value to get the original data using the application key (APP_KEY). Used for sensitive user data like SSNs or API tokens stored in the DB.

Q8: What is the difference between `encrypt` and `hash`?

Encryption: Two-way process. Data is scrambled using a key and can be unscrambled (decrypted) using the same key. Used for sensitive data you need to retrieve later (e.g., credit card tokens, PII).

Hashing: One-way process. Data is scrambled into a fixed-length string and cannot be reversed. Used for verifying data integrity, such as passwords.

Q9: How do you secure API routes in Laravel?

Sanctum / Passport: Use Laravel Sanctum for SPA or simple token-based authentication. Use Passport for full OAuth2 implementation.

Throttling: Apply rate limiting middleware (throttle:api) to prevent abuse.

HTTPS: Always enforce HTTPS to encrypt data in transit.