繁体   English   中英

基于 Laravel 会话的 auth:api 中间件不起作用

[英]Laravel session based auth:api middleware not working

我尝试使用 Laravel 5.3 的 Auth Scaffolding,包括 api 路由。 我想将会话驱动程序用于 api 守卫,但显然这没有任何影响。 在我使用有效用户登录应用程序后(所以我从/login进入/home ),我尝试输入路径/api/user ,但它总是将我重定向到/home RedirectIfAuthenticated中间件重定向用户。

以下是我的尝试以及测试应用程序的快速概览:

// In "app\Http\Middleware\RedirectIfAuthenticated.php"
if (Auth::guard($guard)->check()) {
    return redirect('/home');
}

$guard为空,浏览到/api/user时 if 为真。

// In "config\auth.php"
'api' => [
    'driver' => 'session', // changed from token to session
    'provider' => 'users',
],

我将 api 守卫的驱动程序更改为session

// In "app\Http\Kernel.php"
'api' => [
    'throttle:60,1',
    'bindings',
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Session\Middleware\StartSession::class,
],

我在api中间件中添加了中间件来支持cookies

// In "routes\api.php"
Route::get('/user', function (Request $request) {
    return $request->user();
})->middleware('auth:api');

这是一个新的 Laravel 安装附带的示例。

// In "app\Providers\RouteServiceProvider.php"
Route::group([
    'middleware' => 'api',
    'namespace' => $this->namespace,
    'prefix' => 'api',
], function ($router) {
    require base_path('routes/api.php');
});

api中间件应用于api.php文件中定义的所有路由。

我希望能够在用户登录后在不使用令牌等的情况下查询我的 API。我用 Laravel 5.2 编写的应用程序具有基本相同的路由,但只应用了web中间件组和auth中间件。 在 Laravel 5.3 中,添加auth中间件会导致上述问题。

编辑:通过我的配置,我尝试了以下操作:

// In "routes\web.php"
Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth']);

这工作得很好,但事实并非如此,尽管auth.phpwebapi防护完全相同。

Route::get('/test', function (Request $request) {
    return "test";
})->middleware(['auth:api']);

即使我已经登录,我也遇到了在访问我的 API 路由时被重定向到/home的相同问题。尝试更改App\\Http\\Kernel.php api 中间件的顺序并将bindings放在最后一个位置,以便您的自定义首先执行中间件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM