Skip to content

Commit 7be9472

Browse files
authored
Adding support for X-CSRF-TOKEN - Http header
Order: 1. $_POST 2. HTTP HEADER 3. php://input - trying to parse posted JSON (last because of performance)
1 parent 47933f7 commit 7be9472

1 file changed

Lines changed: 18 additions & 6 deletions

File tree

system/Security/Security.php

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,15 @@ class Security
7575
*/
7676
protected $CSRFTokenName = 'CSRFToken';
7777

78+
/**
79+
* CSRF Header name
80+
*
81+
* Token name for Cross Site Request Forgery protection cookie.
82+
*
83+
* @var string
84+
*/
85+
protected $CSRFHeaderName = 'CSRFToken';
86+
7887
/**
7988
* CSRF Cookie name
8089
*
@@ -171,6 +180,7 @@ public function __construct($config)
171180
// Store our CSRF-related settings
172181
$this->CSRFExpire = $config->CSRFExpire;
173182
$this->CSRFTokenName = $config->CSRFTokenName;
183+
$this->CSRFHeaderName = $config->CSRFHeaderName;
174184
$this->CSRFCookieName = $config->CSRFCookieName;
175185
$this->CSRFRegenerate = $config->CSRFRegenerate;
176186

@@ -206,12 +216,14 @@ public function CSRFVerify(RequestInterface $request)
206216
{
207217
return $this->CSRFSetCookie($request);
208218
}
209-
210-
// Do the token exist in _POST or php://input (json) data?
211-
$CSRFTokenValue = $_POST[$this->CSRFTokenName] ??
212-
(!empty($input = file_get_contents('php://input')) && !empty($json = json_decode($input)) && json_last_error() === JSON_ERROR_NONE ?
213-
($json->{$this->CSRFTokenName} ?? null) :
214-
null);
219+
220+
// Do the tokens exist in _POST, HEADER or optionally php:://input - json data
221+
$CSRFTokenValue = $_POST[$this->CSRFTokenName] ??
222+
(!is_null($request->getHeader($this->CSRFHeaderName)) && !empty($request->getHeader($this->CSRFHeaderName)->getValue()) ?
223+
$request->getHeader($this->CSRFHeaderName)->getValue() :
224+
(!empty(file_get_contents('php://input')) && !empty($json = json_decode(file_get_contents('php://input'))) && json_last_error() === JSON_ERROR_NONE ?
225+
($json->{$this->CSRFTokenName} ?? null) :
226+
null));
215227

216228
// Do the tokens exist in both the _POST/POSTed JSON and _COOKIE arrays?
217229
if (! isset($CSRFTokenValue, $_COOKIE[$this->CSRFCookieName]) || $CSRFTokenValue !== $_COOKIE[$this->CSRFCookieName]

0 commit comments

Comments
 (0)