Search code examples
phplaravelauthenticationlaravel-sanctumlaravel-jetstream

Laravel Jetstream - Is Sanctum required to protect the web routes?


We're using the latest version of Laravel with Laravel Jetstream and want to implement a functionality to allow our admins to sign in on behalf of a regular user. This allows us to provide a better support if some users encounter problems with their accounts.

This function seems perfect to achieve the intended result:

Auth::loginUsingId(1);

Unfortunately I recieve the the following error message

Method Illuminate\Auth\RequestGuard::loginUsingId does not exist

After some time and thanks to the help of Laravel Debugbar I figured out that the problem is caused by Laravel Sanctum. It does not include the above function and is set as middleware to protect the routes in the app\routes\web.php file.

It seems to work after changing the middleware from

Route::middleware(['auth:sanctum', 'verified'])

to

Route::middleware(['auth', 'verified'])

So long story short: Is there another solution to do this? Or better: is this even a valid solution? Can I just remove Sanctum from the web routes or is this requiered for some reason? We want to still use Sanctum to authenticate our mobile applications our token based API.


Solution

  • Sanctum provides a simple mechanism (compared to Passport) for authentication of your APIs and SPAs (served by an API).

    If you're not developing a SPA you are not required to make use of the auth:sanctum middleware and can instead make use of the web auth middleware.

    You can still and should make use of the sanctum middleware in your routes/api.php file.