[英]How do I set up middleware in laravel
所以我有我的身份驗證中間件,它在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
對於您問題的第二部分,請參閱文檔以了解如何將中間件應用於控制器和路由中的特定操作:
http://laravel.com/docs/master/controllers#controller-middleware http://laravel.com/docs/master/routing#route-group-middleware
對於第一部分,您是否嘗試過從終端運行“composer dump-autoload”?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.