Php 使用空间权限时出现Laravel 5.6会话超时异常
我一直在尝试在会话超时后重定向用户,但当使用Spatial permissions软件包时,我无法获得会话超时的令牌不匹配异常,我总是得到UnauthorizedException。以下是我的Exceptions/Handler.php文件:Php 使用空间权限时出现Laravel 5.6会话超时异常,php,laravel,laravel-5.6,spatie,Php,Laravel,Laravel 5.6,Spatie,我一直在尝试在会话超时后重定向用户,但当使用Spatial permissions软件包时,我无法获得会话超时的令牌不匹配异常,我总是得到UnauthorizedException。以下是我的Exceptions/Handler.php文件: public function render($request, Exception $exception) { if ($exception instanceof TokenMismatchException){ sessi
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);
}
在这种情况下,如何捕获会话超时异常并进行自定义重定向?听起来像是在管道中的
验证CSRFTOKEN
之前对包的RoleMiddleware
进行了评估。从它们的源代码中,您可以看到,如果用户未登录,它会立即抛出未授权异常
:
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,
];
查看
illighted\Foundation\Http\Kernel
中定义的中间件的顺序,并解决这个问题。听起来像是在管道中的VerifyCsrfToken
之前对包的rolemidware
进行了评估。从它们的源代码中,您可以看到,如果用户未登录,它会立即抛出未授权异常
:
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,
];
查看
illumb\Foundation\Http\Kernel
中定义的中间件顺序,并解决该问题。try\illumb\Session\tokenmischException而不是tokenmischException try\illumb\Session\tokenmischException而不是tokenmischException