How to return 403 response in JSON format in Laravel 5.2?

房东的猫 提交于 2019-12-10 12:30:04

问题


I am trying to develop a RESTful API with Laravel 5.2. I am stumbled on how to return failed authorization in JSON format. Currently, it is throwing the 403 page error instead of JSON.

Controller: TenantController.php

class TenantController extends Controller
{
    public function show($id)
    {
        $tenant = Tenant::find($id);
        if($tenant == null) return response()->json(['error' => "Invalid tenant ID."],400);
        $this->authorize('show',$tenant);
        return $tenant;
    }
}

Policy: TenantPolicy.php

class TenantPolicy
{
    use HandlesAuthorization;
    public function show(User $user, Tenant $tenant)
    {
        $users = $tenant->users();
        return $tenant->users->contains($user->id);
    }
}

The authorization is currently working fine but it is showing up a 403 forbidden page instead of returning json error. Is it possible to return it as JSON for the 403? And, is it possible to make it global for all failed authorizations (not just in this controller)?


回答1:


We managed to resolve this by modifying the exceptions handler found in App\Exceptions\Handler.php adding it in the render function.

public function render($request, Exception $e)
{
    if ($e instanceof AuthorizationException)
    {
        return response()->json(['error' => 'Not authorized.'],403);
    }
    return parent::render($request, $e);
}



回答2:


Yes, make a simple before method in your policy which will be executed prior to all other authorization checks,

public function before($user, $ability,Request $request)
{
    if (!yourconditiontrue) {
         if ($request->ajax()) {
            return response('Unauthorized.', 401);
        } else {
            return abort('403');
        }
    }
}



回答3:


You can intercept the exception

    try {
        $this->authorize('update', $data);
    } catch (\Exception $e)
    {
        return response()->json(null, 403);
    }


来源:https://stackoverflow.com/questions/38580890/how-to-return-403-response-in-json-format-in-laravel-5-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!