Laravel 5.2: session 和 token guard 在同一条路线上
Laravel 5.2: session and token guard on the same routes
我们有 session 个后卫,这就足够了。
现在我们需要通过令牌(在 headers 或 GET 参数中)和通过 session 在相同的路由上添加授权.
通过令牌授权必须是无状态的。
更新:
首先,我们考虑创建重复路由。
一个用于session,一个用于令牌
// api token auth
// url: /api/test
Route::group(['middleware' => ['web', 'auth:api'], 'prefix' => 'api', 'as' => 'api.'], function () {
Route::resource('test', 'TestController');
// 50+ routes
});
// session auth
// url: /test
Route::group(['middleware' => ['web', 'auth']], function () {
Route::resource('test', 'TestController');
// 50+ routes
});
但这不是我们想要的,因为 url 不同。
也许有人知道如何解决这个问题?
创建新的中间件 AuthenticateWithToken:
class AuthenticateWithToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (($user = Auth::guard('api')->user())) {
Auth::setUser($user);
}
return $next($request);
}
}
在Http/Kernel中声明。php:
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
// ...
'auth.api' => \App\Http\Middleware\AuthenticateWithToken::class,
// ...
];
并在routes.php中的默认'auth'中间件之前添加:
Route::group(['middleware' => ['web', 'auth.api', 'auth']], function () {
Route::resource('test', 'TestController');
// 50+ routes
});
我们有 session 个后卫,这就足够了。
现在我们需要通过令牌(在 headers 或 GET 参数中)和通过 session 在相同的路由上添加授权.
通过令牌授权必须是无状态的。
更新: 首先,我们考虑创建重复路由。 一个用于session,一个用于令牌
// api token auth
// url: /api/test
Route::group(['middleware' => ['web', 'auth:api'], 'prefix' => 'api', 'as' => 'api.'], function () {
Route::resource('test', 'TestController');
// 50+ routes
});
// session auth
// url: /test
Route::group(['middleware' => ['web', 'auth']], function () {
Route::resource('test', 'TestController');
// 50+ routes
});
但这不是我们想要的,因为 url 不同。
也许有人知道如何解决这个问题?
创建新的中间件 AuthenticateWithToken:
class AuthenticateWithToken
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @param string|null $guard
*
* @return mixed
*/
public function handle($request, Closure $next, $guard = null)
{
if (($user = Auth::guard('api')->user())) {
Auth::setUser($user);
}
return $next($request);
}
}
在Http/Kernel中声明。php:
/**
* The application's route middleware.
*
* These middleware may be assigned to groups or used individually.
*
* @var array
*/
protected $routeMiddleware = [
// ...
'auth.api' => \App\Http\Middleware\AuthenticateWithToken::class,
// ...
];
并在routes.php中的默认'auth'中间件之前添加:
Route::group(['middleware' => ['web', 'auth.api', 'auth']], function () {
Route::resource('test', 'TestController');
// 50+ routes
});