【问题标题】:Laravel session based auth:api middleware not working基于 Laravel 会话的身份验证:api 中间件不起作用
【发布时间】:2017-03-29 21:54:55
【问题描述】:

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

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

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

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

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

我把api guard的驱动改成了session

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

我在api中间件中添加了支持cookie的中间件

// 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']);

虽然webapi 守卫在auth.php 内部完全相同,但它工作得非常好。

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

【问题讨论】:

标签: php laravel laravel-5.3


【解决方案1】:

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

【讨论】:

  • 感谢您的回复 - 我所缺少的只是在绑定之前有开始会话课程!
猜你喜欢
  • 1970-01-01
  • 2014-05-09
  • 1970-01-01
  • 2021-05-30
  • 1970-01-01
  • 2011-09-27
  • 2018-05-24
  • 2014-01-31
  • 1970-01-01
相关资源
最近更新 更多