Welcome Guest, Not a member yet? Register   Sign In
Is it possible to enable CSRF protection for RESTful method like PUT and DELETE
#1

(This post was last modified: 05-18-2016, 06:25 AM by dangyuluo.)

I'm building a RESTful API and use several HTTP verbs like PUT, DELETE and of course POST to accept web client request and doing corresponding process. The post request can be protected by enabling CSRF protection in config, which prevents the user from posting the same thing by ajax again and again. But I've tried performing an ajax PUT and DELETE request, but the CSRF protection seems not working. Does it only protect POST request?
Reply
#2

The CSRF config part is as follows:
Code:
$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array('api');

Quiet common. The document of Security Class(here) says:
Quote:CodeIgniter provides CSRF protection out of the box, which will get automatically triggered for every non-GET HTTP request, but also needs you to create your submit forms in a certain way. This is explained in the Security Library documentation.

But actually the test result is: (pls neglect the wrong word delete)
[Image: QQ20160518-0@2x.png]
Reply
#3

While danglyuluo is correct, I personally wouldn't use it in an API for 2 reasons:

1. Most API's are designed to be stateless, and using a cookie to store that information doesn't allow it to be stateless.
2. This is the more important one. CSRF stands for Cross-Site Request Forgery and, by their very nature, most API's are called from somewhere other than the main site, like third-party sites, mobile apps, etc. So most API's would fail those checks anyway since they wouldn't know the nonce that our CSRF protection creates.

However, if you're only using the API through AJAX on your own site, you can use get_csrf_token_name() and get_csrf_hash() to insert those into your javascript at runtime. If you do this, you would need to set $config['csrf_regenerate'] = FALSE; because otherwise CSRF tokens are regenerated for every request so your AJAX methods would have invalid hashes.
Reply




Theme © iAndrew 2016 - Forum software by © MyBB