【问题标题】:Laravel: How to prevent TokenMismatchException when idle?Laravel:空闲时如何防止 TokenMismatchException?
【发布时间】:2017-03-26 01:28:05
【问题描述】:

我一直在遭受这个 TokenMismatchException。所以我正在弄清楚导致错误的原因。我发现如果我尝试将登录页面闲置 15 分钟然后登录。我得到了 TokenMismatchException。我有一个 {!! csrf_field() !!} 在登录表单中。

我的 config/session.php 生命周期设置为 15 分钟。所以我等了 15 分钟才发现 TokenMismatchException 错误。

所以我尝试了这几种解决方案

  1. 已安装 laravel-caffeine
  2. <meta name="csrf-token" content="{{ csrf_token() }}" />
  3. 编辑了 Handler.php

    public function render($request, Exception $e) { if ($e instanceof TokenMismatchException) { return redirect('/login')->with('message', 'Security token expired. Please, login back.'); } if ($e instanceof \Illuminate\Session\TokenMismatchException) { return redirect('/login')->with('message', 'Security token expired. Please, login back.'); } return parent::render($request, $e); }

但似乎没有任何效果。

【问题讨论】:

  • 你不需要 laravel-caffeine。很可能您的异常捕获器是正确的,只是名称空间错误或位于错误的位置
  • @Kenyon ,检查我的代码,我尝试使用 2 个异常。还是不行。
  • 我从这里复制了答案stackoverflow.com/a/31846916/7146565

标签: laravel csrf


【解决方案1】:

你走在正确的轨道上。你可以像这样编辑App\Exceptions\Handler

public function render($request, Exception $e)
{

    if($this->isTokenMismatchException($e)) {

        if(!(Auth::check()))  return $this->redirectGuestToLogin();

    } 

    return parent::render($request, $e);
}

protected function redirectGuestToLogin(){

    return redirect()->guest('auth/login');

}

protected function isTokenMismatchException(Exception $e){

      return $e instanceof TokenMismatchException;

}

【讨论】:

  • 你知道处理程序是否被调用,是否检测到 TokenMismatchException?
  • 我真的不知道。
  • 在每个 if 块中添加 Log::info("Some text") 以查看它们是否有效。然后,您可以在日志中查看执行了哪些代码
  • 等等,我需要检查我是否使用了正确的文件。
【解决方案2】:

我在 Handler 中的代码是正确的。但我的错误是我在浏览器中使用的是旧版本的项目。这就是为什么我仍然收到错误。现在它完全可以工作了。

【讨论】:

  • 我不明白关于using the older version of the project in the browser 的错误。能详细解释一下吗?
  • 实际项目应该是“localhost/myrcf-version-3”,而我一直在运行“localhost/myrcf”。
猜你喜欢
  • 2017-11-18
  • 2011-09-12
  • 1970-01-01
  • 1970-01-01
  • 2019-08-27
  • 2017-08-11
  • 1970-01-01
  • 2020-05-13
相关资源
最近更新 更多