Anyone got JS fetch() to work with CSRF?

Not sure how to send CSRF correctly so that Yii 1.1 gets it. This is a POST request.

  1. Which content type? JSON? Or multiform?

  2. Should YII_CSRF_TOKEN be included in body? As URL string or JSON string?

  3. Credentials should be either “inline” or “same-origin”?

I think I’ve tried all combinations without success. :joy:

Fetch docs: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

Yii 1.1 CSRF validation: https://github.com/yiisoft/yii/blob/master/framework/web/CHttpRequest.php#L1342

For some reason, $_POST and $_REQUEST are always empty in that method.

Yeah OK, got it to work with

'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8',    

in header, and

body: new URLSearchParams({
  YII_CSRF_TOKEN: token,
}).toString(),

for the body.

Also

credentials: 'include'
1 Like