Laravel中的guest和auth中间件有什么区别



//kernel.php

protected $routeMiddleware = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'bindings' => IlluminateRoutingMiddlewareSubstituteBindings::class,
'cache.headers' => IlluminateHttpMiddlewareSetCacheHeaders::class,
'can' => IlluminateAuthMiddlewareAuthorize::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'signed' => IlluminateRoutingMiddlewareValidateSignature::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'verified' => IlluminateAuthMiddlewareEnsureEmailIsVerified::class,
];

我应该使用什么,auth或guest中间件进行身份验证?auth和guest中间件之间的区别是什么?

Auth中间件

确定用户是否已登录到任何防护。如果没有登录,它将抛出AuthenticationException并重定向到登录页面。

来宾中间件

在这里,它将检查用户是否登录到任何防护。如果是,则重定向到RouteServiceProvider::HOME提到的页面。否则它将传递到请求的页面。

如果您想保护您的路由不受非登录用户的影响,请使用auth middleware

auth中间件-用于会话身份验证。auth中间件检查用户是否经过身份验证。如果用户没有会话,那么此路由将把请求重定向到登录路由。

/**
* Get the path the user should be redirected to when they are not authenticated.
*
*/
protected function redirectTo($request)
{
if (! $request->expectsJson()) {
return route('login');
}
}

来宾中间件-此中间件逻辑是,如果用户已登录,则将其重定向到RouteServiceProvider::HOME

public function handle(Request $request, Closure $next, ...$guards)
{
$guards = empty($guards) ? [null] : $guards;
foreach ($guards as $guard) {
if (Auth::guard($guard)->check()) {
return redirect(RouteServiceProvider::HOME);
}
}
return $next($request);
}

可以在AppProvidersRouteServiceProvider中设置RouteServiceProvider::HOME路径

最新更新