Ajax requests not open to everyone

天大地大妈咪最大 提交于 2019-12-01 04:20:13

问题


I've created a webapp using CodeIgniter. There are several places where I use ajax in the application.

I want to know if there is a way where I can stop direct access and query to the ajax controller and only allow legitimate ajax requests originating from the page to be processed.

Thanks.


回答1:


Yes you can do this without a problem. The CodeIgniter input class has a method called is_ajax_request(). Simply check for this at the start of your controller action. For example:

function ajax_save() {
    if ($this->input->is_ajax_request()) {
        //continue on as per usual
    } else {
        show_error("No direct access allowed");
        //or redirect to wherever you would like
    }
}

If you have controllers that are designated completely for ajax calls, you can put that if statement into the constructor function __construct() for the controller. Remember to call parent::__constructor() first though!

Edit: As for "originating from the page", you should probably be doing authentication + security checks (likely via session so that you don't hit the database) on your ajax request. So a rogue user not affiliated with your webapp shouldn't be able to send an ajax request manually anyways. Hope this answers your question.



来源:https://stackoverflow.com/questions/8121997/ajax-requests-not-open-to-everyone

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