0

I am using a predefined response format for all my ajax calls.

If the request is success then the server will respond :

{"status":true,"data":{"name":"person","age":2}}

Please note data is not necessary.

and if the request failed then i will get

{"status":false,"reason":"You are not authorised."}

SO every response have a status field , if status is FALSE then there will be reason field.

The problem is that now i enables CSRF protection in Codeigniter and if the token expired/failed the system outputs

The action you have requested is not allowed.

this is HTML content.

Is it possible to extend the security class ,so that if the request is through Ajax then it will keep json_encoded format else use the html format.(i do not want to modify the core)

Thanks.

1

1 Answer 1

2

This error message is rendered from the CI_Exceptions::show_error method (located in system/core). You can extend this class by the usual way and override this method in order to catch this error and return whatever you want.

You can get rid of the call inside the CI_Security::csrf_show_error method by overriding it so it won't simply call

show_error('The action you have requested is not allowed.');

This is probably more robust.

Alternatively you can attack this inside CI_Exceptions class. Since this errors doesn't come with specific error code you will have to match for the message which could break between updates (currently hardcoded). The resulting class could look like this:

class MY_Exceptions extends CI_Exceptions {
    public function show_error($heading, $message, $template = 'error_general', $status_code = 500) {
        if ($message == 'The action you have requested is not allowed.') {
            // handle this error your way
        } else {
            // send every other error to the original handler
            parent::show_error($heading, $message, $template, $status_code);
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.