Laravel 5.6 使用 spatie 权限时会话超时异常

Laravel 5.6 session timeout exception when using spatie permissions

我一直在尝试在会话超时后重定向用户,但是当使用 spatie 权限包时,我无法获得会话超时的 TokenMismatchException,我总是得到 UnauthorizedException。这是我的 Exceptions/Handler.php 文件:

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

    if ($exception instanceof TokenMismatchException){


        session()->flash('warning','Session timeout. Please login again.');
        return redirect()->guest(route('login'));
    }



    if ($exception instanceof \Spatie\Permission\Exceptions\UnauthorizedException){


        return redirect('/restricted');
    }



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

如何捕获会话超时异常并在这种情况下进行自定义重定向?

听起来好像在管道中的 VerifyCsrfToken 之前评估包的 RoleMiddleware。从他们的源代码中,您可以看到如果用户未登录,它会立即抛出 UnauthorizedException

namespace Spatie\Permission\Middlewares;
use Closure;
use Illuminate\Support\Facades\Auth;
use Spatie\Permission\Exceptions\UnauthorizedException;
class RoleMiddleware
{
    public function handle($request, Closure $next, $role)
    {
        if (Auth::guest()) {
            throw UnauthorizedException::notLoggedIn();
        }
        $roles = is_array($role)
            ? $role
            : explode('|', $role);
        if (! Auth::user()->hasAnyRole($roles)) {
            throw UnauthorizedException::forRoles($roles);
        }
        return $next($request);
    }
}

您可以通过在内核中设置 $middlewarePriority 属性 来修改中间件的顺序,但是,请注意这可能会导致意想不到的副作用:

protected $middlewarePriority = [
    \App\Http\Middleware\MyMiddleware::class,
];

查看 Illuminate\Foundation\Http\Kernel 中定义的中间件的顺序并解决这个问题。