Laravel 5.3 -重定向登录失败


Laravel 5.3 - Failed login attempt redirect

在我的应用程序中,我使用Laravel 5.3的默认身份验证。我有两个用户可以登录的地方,我希望在登录失败的情况下,只重定向到这两个地方中的一个。换句话说,无论用户通过什么视图登录,如果他们提交了无效的凭据,他们总是会被重定向到一个特定的视图,而不是他们从哪个视图提交表单。在Laravel 5.1中,这似乎可以通过在登录控制器中包含$loginPath变量来实现。在Laravel 5.3中,他们似乎已经把这个选项从文档中删除了,所以我不确定如何再处理这个问题了。

任何想法和/或建议都是非常感谢的。谢谢!

编辑:我误解了你最初的问题。

如果你需要自定义这个,你可以这样做:

打开App'Http'Controllers'Auth'LoginController(根据文档,这将是由我假设您使用的php artian make:auth命令生成的)并添加以下内容:

/**
 * Get the failed login response instance.
 *
 * @param 'Illuminate'Http'Request  $request
 * @return 'Illuminate'Http'Response
 */
protected function sendFailedLoginResponse(Request $request)
{
    return redirect()->to('/the_redirect_location')
        ->withInput($request->only($this->username(), 'remember'))
        ->withErrors([
            $this->username() => Lang::get('auth.failed'),
        ]);
}

这将覆盖LoginController使用的'Illuminate'Foundation'Auth'AuthenticatesUsers特性中包含的相同方法。redirect()->to('/the_redirect_location')是我改变的部分。原来是:redirect()->back() .

如果您选择使用此方法,请确保在LoginController:

的顶部添加此内容。
use Lang;
use Illuminate'Http'Request;

如果有人正在寻找Laravel版本5.7的解决方案。我能够通过将以下sendFailedLoginResponse方法添加到LoginController

来完成此工作。
/**
 * Get the failed login response instance.
 *
 * @param  'Illuminate'Http'Request  $request
 * @return 'Symfony'Component'HttpFoundation'Response
 *
 * @throws 'Illuminate'Validation'ValidationException
 */
protected function sendFailedLoginResponse()
{
    throw ValidationException::withMessages([
        $this->username() => [trans('auth.failed')],
    ])
    ->redirectTo("/the_redirect_location");
}

不要忘记以下导入:

use Illuminate'Validation'ValidationException;

注意:这个方法和它从Illuminate'Foundation'Auth'AuthenticateUsers中覆盖的方法的区别在于->redirectTo(" /the_redirect_location");

其中/the_redirect_location是身份验证失败时要重定向到的URL

打开文件Authenticate.php,并像这样为每个您想要重定向的失败路由更改redirectTo()方法。

protected function redirectTo($request) {
  if (! $request->expectsJson()) {
    if ($request->path() == "user/dashboard"){
      return route('user.login.form');
    } else {
      return route('HOME');
    }
  }
}

我在使用带有强化身份验证的Laravel 8时遇到了这个问题,在搜索"Laravel登录失败重定向到首页"后找到了进入这个页面的方法。

如果你遇到的问题是用户被重定向到主页,而不是在他们登录错误时看到错误消息,解决方案是将你的referer - policy从"strict-origin"更改为"strict-origin"。same-origin"帮助"。这个问题记录在这里:https://www.sentinelstand.com/article/laravel-redirects-break-when-using-origin-referrer-policyhttps://laracasts.com/discuss/channels/laravel/laravel-8-fortify-redirect-after-fail-login

要解决这个问题,你的。htaccess应该包含这样的内容:
Header set Referrer-Policy "same-origin"