React Fetch to Laravel API Creates New Session
Laravel automatically generates a CSRF "token" for each active user session managed by the application. This token is used to verify that the authenticated user is the one actually making the requests to the application. : https://laravel.com/docs/5.4/csrf
APIs are stateless. There is nothing like session
in APIs. So you shouldn't use CSRF token in API. If you check Kernel.php
of laravel. You will see Tylor didn't add VerifyCsrf
middleware in API group. Which suggest that CSRF
is only used in the request having session i.e, stateful request. I would recommend you to use JWT based authentication system for API. For more about JWT check here.
You can use this laravel package for JWT : https://github.com/tymondesigns/jwt-auth
I'm not sure what is your request URL and what is your target API url. Make sure both are on same domain(including subdomain).
I think its a good idea to disable CSRF validation only for API routes as these might be used by other domains, native apps etc
You can do that by adding following class file: app/Http/Middleware/VerifyCsrfToken.php
<?phpnamespace App\Http\Middleware;use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as BaseVerifier;class VerifyCsrfToken extends BaseVerifier{ /** * The URIs that should be excluded from CSRF verification. * * @var array */ protected $except = [ 'api/*', ];}
Make sure to edit Kernal.php
to point to the new class:
protected $middleware = [ 'csrf' => 'App\Http\Middleware\VerifyCsrfToken'];
To learn more how Laravel uses CSRF check this laracast video