Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating API for web app with CodeIgniter CSRF protection

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.

like image 280
Shivam Avatar asked Mar 23 '23 06:03

Shivam


1 Answers

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;
} 
like image 118
MJ X Avatar answered Apr 06 '23 00:04

MJ X