简体   繁体   English

会话在Laravel中到期时,将用户重定向到登录页面

[英]Redirect user to login page when session expires in Laravel

I am trying to redirect a user back to the login page if their session has expired. 如果用户的会话已过期,我正在尝试将用户重定向回登录页面。 I am using Laravel 5.5. 我正在使用Laravel 5.5。 I have edited my RedirectIfAuthenticated file to include the following code in the handle function: 我编辑了我的RedirectIfAuthenticated文件,在handle函数中包含以下代码:

if (!Auth::check()) {
    return redirect()->route('login', ['account' => 'demo']);
}

When I do this, I am receiving the following error message: 当我这样做时,我收到以下错误消息:

Missing required parameters for [Route: login] [URI: /]. 缺少[Route:login] [URI:/]的必需参数。

My login route is inside a subdomain route group which is why I am passing the account parameter. 我的login路由在子域路由组内,这就是我传递account参数的原因。 Here is part of my code in web.php 这是我在web.php代码的web.php

// Subdomain routing
Route::domain('{account}.ems.dev')->group(function () {
    Route::get('/', 'LoginController@show')->name('login');
}

And here is my LoginController@show code: 这是我的LoginController@show代码:

/*
 * Show the login form
 */
public function show($account) {
    // Validate this is a valid subdomain
    $organization = Organization::where('subdomain', $account)->first();

    if ($organization) { 
        return view('login');
    } else {
        return 'This account does not exist.';
    }
}

Nothing I have tried works. 我没有尝试过任何工作。 I keep getting the exact same error message even though I am passing in the required parameters. 即使我传递了所需的参数,我仍然会收到完全相同的错误消息。

Update #1 更新#1

Screenshot of error page: 错误页面的屏幕截图:

在此输入图像描述

Update #2 更新#2

After a little digging around the Whoops! 哎呀之后挖了一下 error page, I see this, protected function unauthenticated is what is causing the problem: 错误页面,我看到这一点, protected function unauthenticated是导致问题的原因:

在此输入图像描述

How do I override this function to add the missing parameter? 如何覆盖此功能以添加缺少的参数?

You can override the unauthenticated() method in your app/Exceptions/Handler.php file to add the missing route parameter. 您可以覆盖app/Exceptions/Handler.php文件中的unauthenticated()方法,以添加缺少的路由参数。

use Illuminate\Auth\AuthenticationException;

class Handler extends ExceptionHandler
{
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        return $request->expectsJson()
            ? response()->json(['message' => $exception->getMessage()], 401)
            : redirect()->guest(route('login', ['account' => $request->route('account')]));
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM