简体   繁体   中英

display error through ajax if action is not authorized in laravel 5.1

for a check on the policy like this in a controller:

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

in the docs for 5.1 we can read:

If the action is authorized, the controller will continue executing normally; however, if the authorize method determines that the action is not authorized, a HttpException will automatically be thrown which generates a HTTP response with a 403 Not Authorized status code. As you can see, the authorize method is a convenient, fast way to authorize an action or throw an exception with a single line of code.

And ok that throws an exception and stops right there the execution of the rest of the code. The problem is this happens in the background and the user doesn't know what's going on. So what I want to do is show a message on the fly (through javascript) if the action fails authorization. I think maybe to do that I have to catch the esception that laravel is throwing and then send the result to my ajax function. eg

if ('status' == 403) {

$auth = 0

return Response()->json($auth);

}

and then in my ajax function check for $auth .. or is there a way to send the exception to tha ajax function directly after authorization fails?

As you see, Laravel will automatically abort the request and respond with the proper HTTP error code 403 Unauthorized. This is also the case with AJAX requests.

Most AJAX libraries like jQuery or Axios can handle HTTP error codes very well. You can just look for the error code 403.

For example in jQuery:

$.ajax('/whatever', {
    // ...
    error: function (xhr) {
        if (xhr.status == 403) {
            alert('Unauthorized');
        }
    }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM