laravel / sanctum

Laravel Sanctum provides a featherweight authentication system for SPAs and simple APIs.
https://laravel.com/docs/sanctum
MIT License
2.76k stars 296 forks source link

Sanctum is not working with `api` middleware #369

Closed besfortoruci closed 2 years ago

besfortoruci commented 2 years ago

Tested with:

Description:

When using sanctum auth in api.php, it is returning message: unauthenticated

// routes/api.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

The same thing works on web.php:

// routes/web.php

Route::middleware('auth:sanctum')->get('/user', function (Request $request) {
    return $request->user();
});

It turns out that 'throttle:api' on Kernel.php is breaking it, and it is also looking for EncryptCookies::class and StartSession::class in order to make it work.

// app/Http/Kernel.php

 'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
            'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

I just tested without throttle:api and added EncryptCookies and StartSession. It works normally, but I believe this is not a fix.

Example:

// app/Http/Kernel.php

'api' => [
            \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class,
+           \App\Http\Middleware\EncryptCookies::class,
+           \Illuminate\Session\Middleware\StartSession::class,
-           'throttle:api',
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
        ],

FYI: disabling 'middleware' => ['web'], on /config/sanctum.php doesn't do anything. This is also removed during breeze api installation.

Steps To Reproduce:

*Laravel Breeze:*

laravel new test
composer require laravel/breeze
php artisan breeze:install api
php artisan migrate
php artisan key:generate
php artisan serve

*Laravel Fortify:*

laravel new test
composer require laravel/fortify
php artisan vendor:publish --provider="Laravel\Fortify\FortifyServiceProvider"
php artisan migrate
php artisan key:generate
php artisan serve
driesvints commented 2 years ago

Hey there,

Can you first please try one of the support channels below? If you can actually identify this as a bug, feel free to open up a new issue with a link to the original one and we'll gladly help you out.

Thanks!

paulchill commented 6 months ago

Was this ever solved? A few months ago i noticed i couldn't get cookie auth working for the SPA in api.php so i loved it to web where it works fine.

Now I'm adding an API/ Mobil end points in api.php and I can't authenticate.