How to protect controller against direct access?

2019-04-11 15:43发布

问题:

I'm using codeigniter with jquery and it would be nice if you explain me how to protect the controller from direct access. For example, I have view with that standard jquery line:

$('#handler').load('tools/get_stats');

Tools it is my controller with function for loading statistics. If I write direct in browser full address of script http://site.com/tools/get_stats, browser open, of course, that data. How to protect direct controller access from browser ? I want my data were loaded only in view, not on controller direct access.

回答1:

The CodeIgniter Input Class has a method called is_ajax_request() for this purpose.

if ($this->input->is_ajax_request()) 
{
    //do something
} 
else 
{
    show_error("No direct access allowed");
    //or redirect
} 

If you have a dedicated Ajax Controller, you can of course include this logic in the __construct() method, otherwise it may be implemented on a method by method basis within your controllers.


See:

  • http://ellislab.com/codeigniter/user_guide/libraries/input.html


回答2:

In general you can't do it in a meaningful way due to the need to provide access and the simplicity of HTTP. Or more basically, you can't deny access to information you need to provide (in this case stateless connection info). The best initial steps are to make sure that the controller only allows access to data that the user should have access to (regardless of how they connect), rather than trying to restrict based on the easily tampered with request information.

That being said, if you have some odd reason to really chase after this, you could use some form of single use token passed with the AJAX request. You could, for instance, generate a random key, persist it somewhere (ideally just in memory in something like a hash table since there should never be a long enough delay to warrant otherwise) and pass it out with the page that will issue the ajax request. The token is passed back with the request and removed, and then that token will no longer be valid. The controller would not be able to be accessed directly since it would need a token.

This would still be able to be worked around since the process could be halted and an issued token used, but it would deter anyone just playing around with curl (so really its not worth the effort).

Long story short, you can't do this in any way that anyone couldn't work around within 10 minutes. Focus on making sure you only expose the data you want no matter how its retrieved.