How to return 403 response in JSON format in Laravel 5.2?
When building a RESTful API, returning raw HTML error pages like 403 Forbidden is often an immediate red flag for clients consuming your application. In your specific scenario using Laravel 5.2, the framework's default behavior when authorization fails within a policy is to redirect the user or display an HTML view. This happens because Laravel treats failed policy checks as global exceptions that trigger the Auth facade or default error responses configured in your application.
To resolve this, you need to intercept the authorization failure and return a JSON response instead of letting the framework render its default HTML page. The most effective way to achieve this globally across your entire application without modifying every controller is by creating a custom exception handler.
First, ensure your policy class correctly throws an exception when access is denied. Your TenantPolicy implementation looks correct in that it returns a boolean, but Laravel 5.2 requires you to explicitly throw an exception when the check fails. If your logic relies on a third-party package like mattias-solomon/laravel-abilities, that package handles the throwing internally. However, if you are using native Laravel policies or a different implementation, you must manually trigger the event.
Here is how you modify the policy to explicitly fail:
class TenantPolicy
{
use HandlesAuthorization; // Ensure this trait is present in your Policy class
public function show(User $user, Tenant $tenant)
{
$users = $tenant->users();
if (!$tenant->users->contains($user->id)) {
throw new AuthorizationException;
}
return true; // Or simply let it pass if using HandlesAuthorization correctly
}
}
Note that HandlesAuthorization is often a trait from the mattias-solomon/laravel-abilities package. If you are not using that specific package and just writing raw policies, the standard Laravel approach (pre-CentricAuth) relies on the authorize method or manual checks. The key here is ensuring an AuthorizationException is thrown.
Next, you need to configure your application to catch this exception and return JSON. In Laravel 5.2, you do this by registering a custom exception handler in AppServiceProvider. Open the app/Providers/AppServiceProvider.php file and modify the register method:
use Illuminate\Support\Facades\Auth;
use Illuminate\Foundation\Inspiring;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Http\Request;
use Symfony\Component\HttpFoundation\Response;
public function register()
{
// ... other bindings
}
public function boot()
{
// Register the handler
$this->app['exception.handle'] = function ($exception, $request) {
if ($exception instanceof AuthorizationException) {
return response()->json([
'error' => 'Forbidden',
'message' => config('auth.failed', 'You are not authorized to access this resource.')
], 403);
}
// Handle other exceptions normally
throw $exception;
};
}
By registering this handler, any time AuthorizationException is thrownâwhether from a policy, middleware, or manual checkâthe application will now respond with a JSON body instead of an HTML page. This satisfies your requirement for a global solution that applies to all controllers without needing repetitive code in each one.
Trade-offs and Considerations
While this approach works well for internal API clients, it introduces a potential pitfall regarding the auth.failed configuration key. The response message currently pulls from config('auth.failed'). This is useful for returning specific messages like "This resource is private" rather than generic system errors. However, if you are building a public-facing API where you want to avoid leaking information about why access was denied (security through obscurity), you might prefer to return a static message or an empty error object.
Another consideration in Laravel 5.2 is the version of the framework itself. The exception handling mechanism has evolved significantly in later versions (Laravel 6+). In modern Laravel, you would typically define this logic in app/Exceptions/Handler.php using the reports method or defining a closure in the service provider as shown above. Since you are on 5.2, the closure registration in AppServiceProvider is the correct and supported pattern for customizing exception responses globally.
If you prefer not to use a global exception handler and want to keep error handling localized, you can wrap your policy logic in a try-catch block within the controller or middleware, but this defeats the purpose of having a centralized, maintainable solution for an entire API suite. The global handler ensures consistency across your codebase, which is crucial for maintaining a professional RESTful API standard.