Currently building a mobile app with Phonegap, I'm able to use the Element API for many features, but when comes the time to use Craft as a loggedin user, I run out of ideas.

I read a lot of things about headless Craft, but I found nothing about the proper way to authenticate outside the Craft installation itself.

First, I achieved something semi-decent with a JWT system and a custom controller to perform a login validation, which works great, and allow me to read from Craft on my controller (with $allowAnonymous = true;, unfortunately)

(For curious eyes, it's far from perfect: https://gist.github.com/rtrudel/49b96ebc93bfd6774ebbe841426e4b6c )

But I do not want to turn off CSRF globally, and I need to use users/save-user to save user profile in-app). The CSRF token value returned by Craft::$app->getRequest(); seems not right for the next ajax calls, which return Bad request, unable to verify your data submission.

So, this brings me out of ideas... do I have another way to login my user from my mobile app and to retrieve the CSRF token correctly in order to do that, and for all the ajax calls my app will do once logged in?

My JWT approach is maybe not as good as expected in the use-case, perhaps I have to think different? I'm open to any idea to make it work as it should.

My main concern is security and efficiency.

Thank you!


1 Answer 1


You could make the CSRF token available via an element API endpoint, then submit the form with that;

'api/csrf-token' => [
      'elementType' => GlobalSet::class,
      'paginate' => false,
      'one' => true,
      'transformer' => function () {
        $newCSRFtoken = Craft::$app->request->getCsrfToken(); // sets a new CSRF cookie;
        return [
          'csrfTokenName' => Craft::$app->config->general->csrfTokenName,
          'csrfToken' => $newCSRFtoken,

*This code is from a user on the discord server, would have linked to it but you can't ¯_(ツ)_/¯

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.