Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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)?

like image 319
Heru S Avatar asked Jul 26 '16 04:07

Heru S


People also ask

How do I return a 403 in laravel?

Chatty Cathy // if post isn't found by $id, show 404 $post = Post::findOrFail($id); // if user isn't owner of post, show 403 if (! Auth::user() || Auth::user()->id != $post->user_id) { abort(403); } return view('post-edit',compact('post'));

What is response JSON in laravel?

JSON response can be sent using the json method. This method will automatically set the Content-Type header to application/json. The json method will automatically convert the array into appropriate json response.


1 Answers

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); } 
like image 113
Heru S Avatar answered Sep 22 '22 12:09

Heru S