How to handle CSRF validation without Twig (headless) #9685
-
I'll preface this entire discussion that you should probably use GraphQL mutations in order to POST data to Craft. I'm unsure if this isn't working by design or not. Let's say I have a headless site on one domain, Craft CP on another. I want to create an entry from the front-end of the headless site, but can't be bothered with GraphQL and mutations. I go the simple route and use JS's So - diving into the internals of Yii and how it manages validation of tokens, it compares the supplied token to the "trueToken" and if they match. https://github.com/yiisoft/yii2/blob/e83a86fd302dfaa3667894be2d734a9fcc854076/framework/web/Request.php#L1827-L1843 For this JS request, refer to the below debugging:
(do note that I'm comparing the
Which would explain the reason for the failure. Looking further into things, I can see that getting the So my question is - is this a bug or expected behaviour? Should this sort of thing be allowed, or not? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
As a quick way to get a demo setup, feel free to check out https://github.com/engram-design/craft-headless-fetch which is using Vite. Just a simple form to submit to try and create an entry.
Use |
Beta Was this translation helpful? Give feedback.
-
Anonymous form submissions aren’t a particularly attractive target for an attacker, so you might just want to disable CSRF validation entirely for guest users. You can do that by adding this to your controller’s public function beforeAction($action)
{
if ($action->id === 'submit' && Craft::$app->user->isGuest) {
$this->enableCsrfValidation = false;
}
return parent::beforeAction($action);
} |
Beta Was this translation helpful? Give feedback.
Anonymous form submissions aren’t a particularly attractive target for an attacker, so you might just want to disable CSRF validation entirely for guest users. You can do that by adding this to your controller’s
beforeAction()
method: