我尝试使用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
为null,浏览到 /api/user
时if为true .
// 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中间件中的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
中间件会导致所描述的问题 .
edit :通过我的配置,我尝试了以下方法:
// In "routes\web.php"
Route::get('/test', function (Request $request) {
return "test";
})->middleware(['auth']);
这完全正常,但事实并非如此,尽管 web
和 api
守卫在 auth.php
内完全相同 .
Route::get('/test', function (Request $request) {
return "test";
})->middleware(['auth:api']);
1 回答
即使我已经登录,我也有同样的问题在访问我的API路由时被重定向到/ home . 尝试在Kernel.php中更改api中间件的顺序并将“绑定”放在最后位置,这样你的自定义中间件就是先执行 .