【问题标题】:How to return custom 403 exception when using Laravel 5.1 authorize method使用 Laravel 5.1 授权方法时如何返回自定义 403 异常
【发布时间】:2016-03-19 06:46:48
【问题描述】:

在 laravel 5.1 中,如果您使用以下方法,您可以在检查能力时返回自定义响应:

if (Gate::denies('update', $post)) {
        return response()->view('errors.403');
}

在使用授权方法时有什么方法可以返回类似的自定义错误:

$this->authorize('update', $post);

上面只是简单地抛出一个状态码为 403 的 http 异常。

【问题讨论】:

  • 在授权方法中使用abort('403')怎么样
  • 你将如何通过它?

标签: laravel laravel-5 laravel-5.1 acl laravel-authorization


【解决方案1】:

我可以通过以下方式做到这一点:

App\Http\Controllers\Controller中添加如下方法:

protected function createGateUnauthorizedException(
    $ability,
    $arguments,
    $message = 'This action is unauthorized.',
    $previousException = null
) {
    throw $previousException;
}

它将重新抛出UnauthorizedException

现在在App\Exceptions\Handler.php 中你可以在render 方法的开头添加:

if ($e instanceof \Illuminate\Auth\Access\UnauthorizedException)  {
    return response()->view('errors.403');
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-27
    • 2021-04-05
    • 2018-08-18
    • 1970-01-01
    • 2014-07-07
    • 2017-12-13
    相关资源
    最近更新 更多