phplaravellaravel-fortify

Laravel Fortify and JSON based registering result in CRSF mismatch


I'm currently toying with Laravel 9.x and Fortify.

For the starter here my environnement :

I try to achieve something I thought was possible from reading the Fortify doc, using a third-party UI (e.g.: Mobile App) to register and login user.

So, following the documentation guide I deactivated the views generation, and migrated the tables and launched my test server using php artisan serve.

Then I try using postman to post the following json to the /register route provided by Fortify.

Postman has been setup with the following headers:

{
  "name": "test1",
  "email": "test1@example.com",
  "password": "MyPassw0rd!",
  "password_confirmation": "MyPassw0rd!"
}

The response returned by the request was an error 419 CSRF Token mismatch, which I understand since Laravel enforce the use of CSRF token.

Therefor I tried to add the /register route to the except array inside the middleware VerifyCsrfToken and tried again and this time I got a 201 created response.

From my understanding since the /register route exists within the web guard hence the CSRF token mechanic.

Since my final goal is to use Fortify with third-party frontend, how can achieve that without putting the route inside the except array (if possible)?

Is there a parameter to change inside config/fortify.php to allow this behavior?

Thanks for reading.


Solution

  • After playing I found the solution inside the middleware section of config/fortify.php

    Replacing

    middleware => ['web'],
    

    with

    middleware => ['api'],
    

    Allow to user the register route without having to deactivate the CSRF on the route .