如何解决Laravel 中的 guest 和 auth 中间件有什么区别?
//kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,'can' => \Illuminate\Auth\Middleware\Authorize::class,'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,];
我应该使用什么,身份验证或访客中间件进行身份验证? auth 和来宾中间件有什么区别?
解决方法
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);
}
您可以在RouteServiceProvider::HOME
中设置App\Providers\RouteServiceProvider
路径
身份验证中间件
确定用户是否登录到任何守卫。如果未登录,则将抛出 AuthenticationException
并重定向到登录页面。
访客中间件
在这里它会检查用户是否登录到任何守卫。如果是,它会重定向到 RouteServiceProvider::HOME
提到的页面。否则它会传递到请求的页面。
如果您想保护您的路由免受非登录用户的影响,请使用 auth middleware
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。