Laravel Sanctum integration
Laravel Sanctum works with Tenancy out of the box, with the exception of the sanctum.csrf-cookie route. You can make some small changes to make the route work.
Making the csrf-cookie route work in the tenant app
Section titled “Making the csrf-cookie route work in the tenant app”To make the sanctum.csrf-cookie route work in the tenant app, do the following:
- Add
'routes' => falseto thesanctum.phpconfig - Move the Sanctum migration (for
personal_access_tokenstable) todatabase/migrations/tenant(the migration is published duringinstall:api, it should be indatabase/migrations- if you don’t have that migration, you can publish it usingphp artisan vendor:publish --tag=sanctum-migrations) - Add the following code to
routes/tenant.phpto override the originalsanctum.csrf-cookieroute:
Route::group(['prefix' => config('sanctum.prefix', 'sanctum')], static function () { Route::get('/csrf-cookie', [CsrfCookieController::class, 'show']) ->middleware([ 'web', InitializeTenancyByDomain::class // Use tenancy initialization middleware of your choice ])->name('sanctum.csrf-cookie');});Making the csrf-cookie route work both in the central and the tenant app
Section titled “Making the csrf-cookie route work both in the central and the tenant app”To use the sanctum.csrf-cookie route in both the central and the tenant apps:
- Follow the steps in the previous section to make the csrf-cookie route work in the tenant app
- Include the
personal_access_tokensmigration indatabase/migrationstoo (either publish it again, or copy it fromdatabase/migrations/tenant) - Remove
'routes' => falsefrom thesanctum.phpconfig - Add the
'universal'middleware to thesanctum.csrf-cookieroute in yourroutes/tenant.php