[英]Laravel 5.2 - Using Auth::check() not working in MIddleware
[英]Using Laravel Auth middleware
Laravel 5.1 的文檔確實很少。我需要清楚地了解如何使用 Auth 中間件保護路由。
文檔告訴將“中間件”=>“身份驗證”參數添加到路由。 或者可以做
public function __construct()
{
$this->middleware('auth');
}
但是如何使用 Auth 中間件進行實際用戶身份驗證並從受保護的路由自動重定向到 /login ?
在 Kernel.php - 在受保護的 $routeMiddleware 下有注冊的中間件,如下所示:
/**
* The application's route middleware.
*
* @var array
*/
protected $routeMiddleware = [
'auth' => 'App\Http\Middleware\Authenticate',
'auth.basic' => 'Illuminate\Auth\Middleware\AuthenticateWithBasicAuth',
'guest' => 'App\Http\Middleware\RedirectIfAuthenticated',
];
您可以看到 'auth' 已注冊使用 App\\Http\\Middleware\\Authenticate。
然后你可以按照這個路徑 - 如果你打開/app/Http/Middleware/Authenticate.php ,你會發現公共函數句柄:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('auth/login');
}
}
return $next($request);
}
這里是管理重定向的地方,您可以根據自己的需要修改它,也可以創建自定義中間件。
最后 - 正如它在文檔中所寫的那樣 - 在需要進行身份驗證的控制器中,您將添加
public function __construct()
{
$this->middleware('auth');
}
如果提供的中間件不適合您的需要,您可以創建自定義中間件。
在 laravel 5.2 上,如果你想隱藏注冊表單或登錄表單視圖,你應該使用你的中間件:
$this->middleware('mymiddleware', ['only' => ['register', 'showRegistrationForm', 'login', 'showLoginForm']]);
或者
$this->middleware('mymiddleware', ['except' => ['register', 'showRegistrationForm', 'login', 'showLoginForm']]);
那是因為 register 和 login 路由是 AuthController 上的 post 方法,而 showXxxxForm 是表單視圖。
希望它可以幫助任何人。
在 Laravel 中,中間件用於某些路由只能在用戶登錄時訪問,否則將重定向到登錄頁面。
Auth::routes();
Route::middleware(['auth'])->group(function () {
//After Login the routes are accept by the loginUsers...
}
Route::middleware(['admin'])->group(function(){
//the Admin is logged in to access the Routes...
}
//使用中間件進行登錄認證
1)制作中間件:
php artisan make:middleware adminAuth
2)寫入中間件文件:
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class loginAuth
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle(Request $request, Closure $next)
{
$isAuthenticatedAdmin = (Auth::check());
//This will be excecuted if the new authentication fails.
if (!$isAuthenticatedAdmin){
return redirect()->route('login')->with('message', 'Authentication Error.');
}
return $next($request);
}
}
3) 在下面一行中添加 app/http/kernal.php
protected $routeMiddleware = [
'adminAuth' => \App\Http\Middleware\AdminAuth::class //Registering New Middleware
];
4)在中間件中添加路由:
Route::get('login',[AuthController::class,'index'])->name('login'); //named route
Route::get('dashboard',function(){
return view('admin-page.dashboard');
})->middleware("adminAuth");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.