Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Security Bundle Laravel Package

nelmio/security-bundle

Symfony bundle adding practical security headers and protections: Content Security Policy, X-Frame-Options clickjacking defense, HSTS/HTTPS enforcement, signed cookies, external redirect detection, and content-type sniffing disablement.

View on GitHub
Deep Wiki
Context7

Getting Started

First Steps

  1. Installation Add the bundle via Composer:

    composer require nelmio/security-bundle
    

    Enable it in config/bundles.php:

    Nelmio\SecurityBundle\NelmioSecurityBundle::class => ['all' => true],
    
  2. Configuration Publish the default config:

    php bin/console nelmio:security:install
    

    Review config/packages/nelmio_security.yaml for:

    • signed_cookies (enable/disable)
    • hsts (HTTP Strict Transport Security)
    • cookie_session_storage (secure session handling)
  3. First Use Case Sign Cookies: Automatically sign sensitive cookies (e.g., remember_me).

    # config/packages/nelmio_security.yaml
    nelmio_security:
        signed_cookies:
            enabled: true
            keys: ['%kernel.project_dir%/var/security/cookie_keys']
    

    Generate keys:

    mkdir -p var/security && openssl rand -hex 32 > var/security/cookie_keys
    

Implementation Patterns

1. Signed & Encrypted Cookies

  • Usage: Protect cookies from tampering (e.g., XSRF-TOKEN, custom auth tokens).
    // In a controller
    $this->get('nelmio_security.cookie_manager')->setSignedCookie(
        'user_prefs',
        ['theme' => 'dark'],
        ['lifetime' => 3600]
    );
    
  • Workflow:
    • Enable in config (signed_cookies.enabled: true).
    • Use CookieManager service to set/get signed cookies.
    • Rotate keys periodically (via nelmio:security:rotate-keys).

2. HTTPS Enforcement

  • Usage: Redirect HTTP → HTTPS and enforce HSTS.
    nelmio_security:
        hsts:
            enabled: true
            max_age: 31536000  # 1 year
            include_subdomains: true
    
  • Integration Tips:
    • Works with Symfony’s FrameworkBundle (no extra middleware needed).
    • Test with curl -v http://your-site.com to verify redirects.
    • Combine with symfony/webpack-encore for asset HTTPS in dev.

3. Cookie-Based Session Storage

  • Usage: Store sessions in cookies (useful for stateless APIs or shared hosting).
    nelmio_security:
        cookie_session_storage:
            enabled: true
            cookie_lifetime: 3600
    
  • Workflow:
    • Configure session.storage.handler_id in framework.yaml:
      session:
          handler_id: nelmio_security.cookie_session_handler
      
    • Useful for serverless or Dockerized apps where shared storage is unavailable.

4. CSRF Protection

  • Usage: Extend Symfony’s CSRF with Nelmio’s cookie-based tokens.
    <form method="POST">
        {{ csrf_token('csrf_token') }}  {# Renders signed token #}
    </form>
    
  • Pattern: Always use csrf_token() in forms. Validate in controllers:
    $this->get('nelmio_security.csrf_token_manager')->validateToken(
        $request->request->get('_csrf_token')
    );
    

5. Custom Security Headers

  • Usage: Add headers like X-Content-Type-Options or X-Frame-Options.
    nelmio_security:
        headers:
            x_frame_options: DENY
            x_content_type_options: nosniff
    
  • Integration: Works alongside Symfony’s security.headers config.

Gotchas and Tips

Pitfalls

  1. Key Management

    • Gotcha: Forgetting to rotate keys (nelmio:security:rotate-keys) breaks signed cookies.
    • Fix: Schedule key rotation (e.g., via cron) and test with:
      php bin/console nelmio:security:rotate-keys --dry-run
      
  2. HSTS Preload

    • Gotcha: Enabling hsts.preload: true requires submitting your site to HSTS Preload List.
    • Fix: Test thoroughly in staging first.
  3. Cookie Size Limits

    • Gotcha: Cookie-based sessions may fail if payload exceeds browser limits (~4KB).
    • Fix: Use session.storage.options to compress data or switch to database storage.
  4. CSRF Token Mismatch

    • Gotcha: Tokens expire or mismatch after key rotation.
    • Fix: Clear old tokens via:
      $this->get('nelmio_security.csrf_token_manager')->clearTokens();
      

Debugging

  • Enable Verbose Logging:

    nelmio_security:
        debug: true
    

    Logs appear in var/log/dev.log.

  • Check Headers: Use curl -I http://your-site.com to verify:

    • Strict-Transport-Security (HSTS).
    • X-CSRF-Token (CSRF protection).

Extension Points

  1. Custom Cookie Namespaces Override default cookie prefixes:

    nelmio_security:
        signed_cookies:
            namespace: 'app_'
    
  2. Event Listeners Extend behavior via events (e.g., nelmio_security.on_cookie_sign):

    // src/EventListener/CustomCookieListener.php
    public function onCookieSign(CookieSignEvent $event) {
        if ($event->getName() === 'user_prefs') {
            $event->setData(['custom_field' => 'value']);
        }
    }
    
  3. Symfony Flex Overrides Customize templates (e.g., twig/config.html.twig) to inject security headers:

    {% block nelmio_security_headers %}
        <meta http-equiv="Content-Security-Policy" content="...">
    {% endblock %}
    

Performance Tips

  • Cache Keys: Store cookie keys in cache (e.g., Redis) for multi-server setups.
  • Lazy-Load Headers: Disable nelmio_security.headers in dev to reduce overhead.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky