Laravel passport gives 401 Unauthenticated error

拥有回忆 提交于 2019-12-03 22:08:41

To answer your question: Yes you can!

In our middleware we do some like this:

config([
  'database.connections.tenant.schema' => $tenant
]);

DB::connection('tenant')->statement("SET search_path = $tenant");

It really sounds to me that your search_path is not set up in properly. This would explain why you get a 401. Because Laravel Passport is searching in the wrong database in which it can't find the right token in your users table.

From PostgreSQL docs (https://www.postgresql.org/docs/9.1/static/runtime-config-client.html):

search_path (string)

This variable specifies the order in which schemas are searched when an object (table, data type, function, etc.) is referenced by a simple name with no schema specified. When there are objects of identical names in different schemas, the one found first in the search path is used. An object that is not in any of the schemas in the search path can only be referenced by specifying its containing schema with a qualified (dotted) name.

This is CORS issue. OPTIONS request does not deliver Authorization headers.

If the origin is different from the host, browser going to send OPTIONS before any other request.

Laravel going to answer with the status 401 if CORS middleware is not set up.

So with RESTful architecture, if the client app host is different from the API's host you have to use CORS middleware.

You may use this one: barryvdh/laravel-cors

$ composer require barryvdh/laravel-cors

Example:

App\Http\Kernel.php

protected $routeMiddleware = [
    ...
    'auth.cors' => \Barryvdh\Cors\HandleCors::class,
    ...
];

web.php

Route::group([
    'prefix' => 'api',
    'middleware' => [
        'auth.cors'
    ]
], function () {
    Route::post('user/authenticate', 'UserController@authenticate');
});

If CORS middleware works properly a browser shall receive status 200 on the OPTIONS request and fire the initial request with a payload.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!