Laravel sanctum change csrf cookie route

Viewed 3352

How could I change laravel sanctum csrf cookie route to /api/sanctum/csrf-cookie ?

I tried adding this to api.php routes:

use Laravel\Sanctum\Http\Controllers\CsrfCookieController;
Route::get('/sanctum/csrf-cookie', CsrfCookieController::class . '@show')->middleware('web');

But it looks for this controller under app/http/controllers where it doesn't exist.

3 Answers

So if anyone wondering, there should be prefix within config file that is default set to 'sanctum' within a package service provider.

So if you want to change it to API routes you should go to config/sanctum.php and add 'prefix' => 'api'.

you can create a controller CsrfController and make it extends (Laravel\Sanctum\Http\Controllers\CsrfCookieController)

use Laravel\Sanctum\Http\Controllers\CsrfCookieController
class CsrfController extends CsrfCookieController {}

and then you can link your route

Route::get('/sanctum/csrf-cookie', 'CsrfController@show')->middleware('web');

another flexible solution is to set

'routes' => false

in config/sanctum.php ,then define a new route in routes\api.php

use Laravel\Sanctum\Http\Controllers\CsrfCookieController;

Route::get('/csrf', [CsrfCookieController::class, 'get'])->name('csrf');

like so, you can choose the proper route to suit your needs

Related