FormRequest授权laravel5.3 / 4失败

时间:2017-02-07 17:16:47

标签: php laravel

我尝试通过formRequest

授权用户
public function authorize()
{
    return Gate::allows('users.create');
}

在验证失败时,我得到403并且在Handler.php第133行中出现错误 HttpException的页面:此操作未经授权。。没关系,但我想用JSON创建自己的响应。我怎样才能做到这一点?对于验证失败,我可以使用 response(),但如果我想处理失败的授权响应怎么办?

我发现 failedAuthorization(),但它返回 Excepiton 。我是对的,Laravel作为响应返回异常(如果打开调试模式)?

我需要通过 authorize()方法授权(或者我更喜欢)用户。

2 个答案:

答案 0 :(得分:0)

根据授权的laravel文档,您可以处理拒绝:

if (Gate::denies('update', $post)) {
    abort(403);
}

https://laravel.com/docs/5.1/authorization#policies

答案 1 :(得分:0)

我重写了 failedAuthorization() 方法以返回 JSON 响应:

    public function failedAuthorization()
    {
        throw new HttpResponseException(response()->json([
            'message' => 'You\'re not authorized to do this request',
            'exception' => 'This action requires more permissions'
        ], Response::HTTP_UNAUTHORIZED));
    }

相关问题