Browse Source

Add option to make CSRF Token HttpOnly.

This option lets users opt-in to http only cookies for CSRF tokens, this
is useful when you have no client-side scripting that needs a CSRF
token.

Refs #7727
Mark Story 10 years ago
parent
commit
f7f5e21d80

+ 3 - 0
src/Controller/Component/CsrfComponent.php

@@ -46,6 +46,7 @@ class CsrfComponent extends Component
      *  - cookieName = The name of the cookie to send.
      *  - expiry = How long the CSRF token should last. Defaults to browser session.
      *  - secure = Whether or not the cookie will be set with the Secure flag. Defaults to false.
+     *  - httpOnly = Whether or not the cookie will be set with the HttpOnly flag. Defaults to false.
      *  - field = The form field to check. Changing this will also require configuring
      *    FormHelper.
      *
@@ -55,6 +56,7 @@ class CsrfComponent extends Component
         'cookieName' => 'csrfToken',
         'expiry' => 0,
         'secure' => false,
+        'httpOnly' => false,
         'field' => '_csrfToken',
     ];
 
@@ -132,6 +134,7 @@ class CsrfComponent extends Component
             'expire' => $expiry->format('U'),
             'path' => $request->webroot,
             'secure' => $this->_config['secure'],
+            'httpOnly' => $this->_config['httpOnly'],
         ]);
     }
 

+ 3 - 1
tests/TestCase/Controller/Component/CsrfComponentTest.php

@@ -265,7 +265,8 @@ class CsrfComponentTest extends TestCase
         $component = new CsrfComponent($this->registry, [
             'cookieName' => 'token',
             'expiry' => '+1 hour',
-            'secure' => true
+            'secure' => true,
+            'httpOnly' => true
         ]);
 
         $event = new Event('Controller.startup', $controller);
@@ -278,6 +279,7 @@ class CsrfComponentTest extends TestCase
         $this->assertWithinRange((new Time('+1 hour'))->format('U'), $cookie['expire'], 1, 'session duration.');
         $this->assertEquals('/dir/', $cookie['path'], 'session path.');
         $this->assertTrue($cookie['secure'], 'cookie security flag missing');
+        $this->assertTrue($cookie['httpOnly'], 'cookie httpOnly flag missing');
     }
 
     /**