Mahamudul Hasan Rubel
HomeBlogCoursesAboutProjectsSkillsExperiencePhotosContact
Mahamudul Hasan Rubel

Senior Software Engineer crafting high-performance web applications and SaaS platforms.

Navigation

  • Home
  • Blog
  • Courses
  • About
  • Projects
  • Skills
  • Experience
  • Photos
  • Contact

Get in Touch

Available for senior/lead roles and consulting.

bd.mhrubel@gmail.comHire Me

Subscribe to the newsletter

Get new articles and course lessons delivered to your inbox. No spam, unsubscribe anytime.

© 2026 Mahamudul Hasan Rubel. All rights reserved.

Built with using Next.js 16 & Tailwind v4

Back to Blog
Lesson 53 of the Advanced Laravel: Architecture, Scaling & Performance course
LaravelJune 28, 20263 min read

Advanced Security Header Configuration: CSP and Secure Cookies in Laravel

Learn how to harden your Laravel application by configuring advanced security headers, implementing a strict CSP, and enforcing secure cookie flags.

LaravelSecurityWebCSPHTTP Headersphpbackend

Previously in this course, we explored custom middleware development to handle request interception and performance optimization. In this lesson, we build upon that foundation by focusing on the browser-server contract: security headers.

While Laravel provides sensible defaults, production-grade SaaS platforms require a more proactive stance against browser-based vulnerabilities like Cross-Site Scripting (XSS), clickjacking, and session hijacking. We will harden our application by implementing a strict Content Security Policy (CSP) and enforcing strict cookie security.

The Defense-in-Depth Approach

Security headers are instructions sent by your server to the client's browser, dictating how it should handle your site's content and cookies. They are the first line of defense against client-side attacks.

Configuring Secure Cookie Flags

Cookie security is often overlooked until a session hijacking incident occurs. Every cookie in your application must explicitly define its scope and security constraints.

In your config/session.php and config/sanctum.php, ensure these flags are set:

  • secure: Ensures the cookie is only sent over HTTPS. Never set this to false in production.
  • http_only: Prevents JavaScript from accessing the cookie via document.cookie, mitigating the impact of XSS.
  • same_site: Controls cross-site request behavior. Set this to lax or strict to prevent CSRF.
PHP
#6A9955">// config/session.php

'secure' => env('SESSION_SECURE_COOKIE', true),
'http_only' => true,
'same_site' => 'lax', #6A9955">// Use 'strict' if your app doesn't rely on cross-site navigation

Implementing a Robust Content Security Policy (CSP)

A Content Security Policy (CSP) tells the browser which sources of content (scripts, styles, images) are trusted. If an attacker manages to inject a malicious script, a properly configured CSP will block it from executing or reporting it to your telemetry endpoint.

Instead of writing raw headers, use a package like spatie/laravel-csp to define your policy in a fluent, object-oriented way.

Worked Example: Defining a Domain-Specific Policy

Create a dedicated policy class in app/Policies/Csp/SaaSProductionPolicy.php:

PHP
namespace App\Policies\Csp;

use Spatie\Csp\Policies\Policy;
use Spatie\Csp\Directive;
use Spatie\Csp\Keyword;

class SaaSProductionPolicy extends Policy
{
    public function configure()
    {
        $this->addDirective(Directive::BASE, Keyword::SELF)
             ->addDirective(Directive::CONNECT, [Keyword::SELF, 'https:#6A9955">//api.stripe.com'])
             ->addDirective(Directive::DEFAULT, Keyword::SELF)
             ->addDirective(Directive::SCRIPT, [Keyword::SELF, 'https:#6A9955">//js.stripe.com'])
             ->addDirective(Directive::STYLE, [Keyword::SELF, 'https:#6A9955">//fonts.googleapis.com'])
             ->addDirective(Directive::IMG, [Keyword::SELF, 'data:', 'https:#6A9955">//res.cloudinary.com']);
    }
}

Register this policy in your AppServiceProvider or via the csp.php config file. This setup ensures that only scripts from your own domain and Stripe are allowed, neutralizing most third-party script injection vectors.

Comparison of Security Headers

HeaderPurposePrimary Threat Prevented
Content-Security-PolicyDefines trusted content sourcesXSS, Data Injection
Strict-Transport-SecurityForces HTTPS connectionMan-in-the-Middle
X-Content-Type-OptionsDisables MIME-type sniffingDrive-by downloads
X-Frame-OptionsPrevents framingClickjacking

Hands-on Exercise

  1. Audit current headers: Use curl -I https://your-app.test to inspect your current headers. Note missing ones like Content-Security-Policy.
  2. Apply HSTS: Configure the Strict-Transport-Security header in your TrustProxies middleware to ensure browsers only connect via HTTPS for the next year.
  3. Implement CSP: Install a CSP package, define your domain's script and style sources, and deploy it in report-only mode first to ensure you don't break existing features.

Common Pitfalls

  • report-only neglect: Always deploy CSP in report-only mode first. Use a logging service or Sentry to monitor violations before switching to enforce.
  • Over-permissive unsafe-inline: Many developers add unsafe-inline to their CSP to fix broken styles or scripts. This effectively disables the main benefit of CSP. Refactor your code to use nonce-based scripts instead.
  • Ignoring Subdomains: If your SaaS uses subdomains (e.g., app.saas.com and marketing.saas.com), ensure your cookies are scoped correctly using the domain key in your session config, or risk session leakage.

Recap

We have moved beyond basic Laravel defaults by:

  1. Enforcing secure, http_only, and same_site flags on all cookies.
  2. Implementing a domain-specific CSP that restricts script and style sources.
  3. Understanding the role of various security headers in mitigating browser-based attacks like XSS and Clickjacking.

By hardening these headers, you ensure that your infrastructure is as resilient as your domain logic.

Up next: We will discuss Database Sharding Concepts and how to plan for data distribution as our SaaS platform scales.

Previous lessonHandling Large Data ExportsNext lesson Database Sharding Concepts
Back to Blog

Similar Posts

LaravelJune 28, 20263 min read

Handling Webhooks Securely: Validation and Queueing in Laravel

Learn to build production-ready integrations by validating webhook signatures and offloading processing to queues to ensure security and system reliability.

Read more
LaravelJune 28, 20263 min read

Automated Security Testing: Hardening Laravel CI/CD Pipelines

Master automated security testing by integrating static analysis and dependency auditing into your Laravel CI/CD pipeline to catch vulnerabilities early.

Part of the course

Advanced Laravel: Architecture, Scaling & Performance

advanced · Lesson 53 of 57

  1. 1

    Transitioning from MVC to DDD

    3 min
  2. 2

    Defining Bounded Contexts

    3 min
  3. 3

    Implementing Action Classes

    3 min
Read more
LaravelJune 28, 20264 min read

Mass Assignment Hardening: Securing Eloquent Models

Mass assignment is a critical security vulnerability where attackers inject unauthorized fields into your database. Learn to harden your Laravel models today.

Read more
4

Utilizing Data Transfer Objects (DTOs)

3 min
  • 5

    Service Layer Pattern

    4 min
  • 6

    Modular Monolith Structure

    3 min
  • 7

    Querying with Strict Eloquent

    4 min
  • 8

    Advanced Subqueries and Joins

    4 min
  • 9

    Raw Expressions for Performance

    4 min
  • 10

    Advanced Indexing Strategies

    4 min
  • 11

    Database Partitioning Techniques

    4 min
  • 12

    Read/Write Database Splitting

    4 min
  • 13

    Handling Multi-Database Connections

    3 min
  • 14

    Eloquent Caching Strategies

    3 min
  • 15

    Queue Worker Prioritization

    4 min
  • 16

    Unique Job Patterns

    4 min
  • 17

    Rate Limiting Background Jobs

    3 min
  • 18

    Event-Driven Architecture

    4 min
  • 19

    Integrating External Message Brokers

    4 min
  • 20

    Distributed Transactions and Sagas

    3 min
  • 21

    Eventual Consistency Patterns

    4 min
  • 22

    Multi-Layered Caching Strategy

    4 min
  • 23

    Cache Tagging and Invalidation

    4 min
  • 24

    Session Persistence in Clusters

    4 min
  • 25

    High-Availability Infrastructure

    4 min
  • 26

    Zero-Downtime Deployment Pipelines

    4 min
  • 27

    Advanced OAuth2 Implementation

    3 min
  • 28

    JWT and Stateless Security

    4 min
  • 29

    Multi-Tenant Security Isolation

    3 min
  • 30

    Defense Against SSRF

    3 min
  • 31

    Mass Assignment Hardening

    4 min
  • 32

    Automated Security Testing

    3 min
  • 33

    Custom Telemetry Design

    3 min
  • 34

    Distributed Tracing

    4 min
  • 35

    Profiling PHP Execution

    3 min
  • 36

    Memory Management in Long-Running Processes

    4 min
  • 37

    Testing DDD Components

    3 min
  • 38

    Contract Testing

    3 min
  • 39

    Handling Large File Uploads

    3 min
  • 40

    Optimizing Asset Pipelines

    4 min
  • 41

    Database Query Caching Layers

    3 min
  • 42

    Advanced Eloquent Scopes

    4 min
  • 43

    Distributed Locks

    3 min
  • 44

    API Versioning Strategies

    4 min
  • 45

    Database Migration Strategies

    4 min
  • 46

    Handling Webhooks Securely

    3 min
  • 47

    Advanced Logging Patterns

    3 min
  • 48

    Database Indexing for Joins

    4 min
  • 49

    Graceful Degradation

    3 min
  • 50

    Custom Middleware Development

    4 min
  • 51

    Database Connection Pooling

    4 min
  • 52

    Handling Large Data Exports

    3 min
  • 53

    Security Header Configuration

    3 min
  • 54

    Database Sharding Concepts

    4 min
  • 55

    Real-time Data Synchronization

    3 min
  • 56

    Database Deadlock Prevention

    4 min
  • 57

    Managing Third-Party API Integrations

    Coming soon
  • View full course