【发布时间】:2015-12-17 12:18:20
【问题描述】:
所以我有我的身份验证中间件,它在Http/Kernel.php 中注册为:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
];
接下来我对Authenticate类中的中间件句柄函数进行了修改:
public function handle($request, Closure $next)
{
if ($this->auth->check()) {
$user = $this->auth->user();
$currentDateTime = strtotime('Y-m-d H:i:s');
$tokenExpirationTile = strtotime($user->token_expiration);
if ($currentDateTime <= $tokenExpirationTile) {
return $next($request);
} else {
$this->auth->logout();
redirect('home/login')->with('message', 'Your session has expired. Please login in again');
}
} else {
redirect('home/login')->with('message', 'Please login before attempting to access that');
}
}
最后我创建了路线:
Route::get('home/dashboard', 'HomeController@dashboard', ['middleware' => 'auth']);
我可以访问这条路线,但作为未登录用户,我应该被重定向。
当我在handle 函数中通过dd() 时,没有任何反应。
如何让它在这条路线上运行这个方法?
另外,当涉及到需要在每个操作请求之前进行身份验证的其他控制器时,您怎么说:“在每个操作之前,运行此方法。”在rails中我会做before_action :method_name
【问题讨论】:
-
你的 dd() 在哪里?如果你把 $this->middleware('auth');在您的 HomeController 构造函数中。根据文档“但是,在控制器的构造函数中指定中间件更方便。”
-
@ExoticChimp 我只希望它适用于特定的控制器操作
-
请查看我回答中的文档。你把它放在你的构造函数中: $this->middleware('auth', ['only' => ['dashboard']]);
标签: php laravel laravel-5 laravel-middleware