Laravel - Passport/SPA 401 Unauthorized
It was a little while ago that we went through the same issue, but I can see we followed the laravel documentation to add a web middleware in kernel.php
:
'web' => [ // Other middleware... // ... // This Adds a cookie containing a JWT token for Laravel Passport \Laravel\Passport\Http\Middleware\CreateFreshApiToken::class,],
Potentially relevant: to simplify our requests to the back-end we had axios setup to prefix requests with api/
, which meant we also had to tell Passport to expect this. In AuthServiceProvider.php
:
Passport::routes(null, ['prefix' => 'api/oauth']);
Hi all i have same issue of Unauthenticated.But my fault is in Postman Header i set Authorization:'Bearer token'. it replace to Authorization:Bearer token.So sad..Now it working
The default oauth routes are assigned the web and auth middleware so you have to find a way to assign them the auth:api middleware.
I also prefer to use an api/oauth prefix for consistency.
In your AuthServiceProvider
Passport::routes(null, array('prefix' => 'api/oauth', 'middleware' => array('auth:api', 'web', 'auth')));
That will give you the api/oauth prefix AND add the auth:api middleware so you can authenticate via Bearer tokens.
Keep in mind you'll encounter some CSRF token issues that using
Passport::ignoreCsrfToken(true);
Doesn't seem to solve.
You'll need to pass in the proper headers (see CSRF Protection under: https://laravel.com/docs/6.x/passport#consuming-your-api-with-javascript):
When using this method of authentication, you will need to ensure a valid CSRF token header is included in your requests. The default Laravel JavaScript scaffolding includes an Axios instance, which will automatically use the encrypted XSRF-TOKEN cookie value to send a X-XSRF-TOKEN header on same-origin requests.