如果未通过身份验证,如何将用户重定向到登录页面?

时间:2020-02-26 09:18:20

标签: laravel

如果用户未通过身份验证,我已经在Google上搜索了很多有关重定向的信息。 他们中的大多数人说去App \ Http \ Middleware \ Autheticated.php。在那里设置了重定向路由。 在教程中,我看到

//this method will be triggered before your controller constructor
public function handle($request, Closure $next)
{
    //check here if the user is authenticated
    if ( ! $this->auth->user() )
    {
        // here you should redirect to login 
    }

    return $next($request);
}

但就我而言

 protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');  
        }
    }

如果我用handle函数替换redirecTo函数,那么它会给我关于兼容性的错误。

如果我在redirectTo函数中删除返回路由(“ login”),那么它总是将我重定向到注册页面。

2 个答案:

答案 0 :(得分:2)

您只需在路由中使用Auth中间件f.ex:

Route::group(['middleware' => 'auth'], function(){
   //Put inside this all the routes that you want to force the login
   Route::get('profile' , 'UserController@profile');
});
//Put outside this all the routes that you want to not force login

如果用户要在不登录的情况下访问中间件路由组中的路由,则中间件会将用户重定向到登录页面

答案 1 :(得分:0)

我在ExceptionHander.php中进行了凭证更改

protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['error' => 'Unauthenticated.'], 401);
        }
        $guard = Array($exception->guards(), 0);
        switch ($guard) {
          case 'admin':
            $login = 'adminloginpage';
            break;
          case 'futsal':
            $login = 'futsalloginpage';
          break;  
          default:
            $login = 'register'; //i changed this to login
            break;
        }
        return redirect()->guest(route($login));
    }

由于该rediectTo函数被覆盖