Creating API for web app with CodeIgniter CSRF protection

api, codeigniter, php, restful-authentication

Solution

check out implementation of CSRF in codeigniter from net.tutsplus.com.

I hope that will solve your problem. if you implemented correctly than write this inside you config.php

if (isset($_SERVER["REQUEST_URI"])) 
{
    if(stripos($_SERVER["REQUEST_URI"],'/mypage') === FALSE)
    {
        $config['csrf_protection'] = TRUE;
    }
    else
    {
        $config['csrf_protection'] = FALSE;
    } 
} 
else 
{
    $config['csrf_protection'] = TRUE;
} 

Problem

I have a web application built using CodeIgniter 2 , I have enabled CSRF protection in it. `$config['csrf_protection'] = TRUE;` My friend is creating mobile app for the same, so he needs API to communicate with Web App. I have created RESTful API in CI using this tutorial . All the request made by mobile app are `POST` request. The problem I am facing is , since CSRF protection is enabled , and POST request made from mobile does not carry any "CSRF Token" so it is throwing `500 internal server error`. However if I disable CSRF protection everything is working fine. What is the correct way to implement it ? Shall I generate token on mobile itself ? Or shall I add exception to CSRF protection ? If so , then how can I do it ? because I don't want to disable CSRF protection.

Original source