• 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
AJAX and CSRF in CI 4.0.4

#1
Hello everyone.
I am new here, but I have already searched and read various things and I cannot find the real and effective solution to my problem.
I have the classic CSRF and AJAX problem, in CodeIgniter 4.0.4. I´m using JQuery 3.5.1 too.


My myFunction() function is automatically executed when the page loads, with JQuery's $ (document) .ready (function () {...})
and it is defined in a .js file, as follows:

var myFunction = function() {
  function onMyFunctionReceived(jsonAnswer) {
     //bla, bla bla
  }
  function onMyFunctionError() {
    //bla, bla bla
  }
  $.ajax({
    url: url,
    data: {[csrfName]: csrfValue, data1: "value1", data2: "value2"},
    type: "POST",
    dataType: "json",
    headers: {[varHdrName]: varValue},
    success: onMyFunctionReceived,
    error: onMyFunctionError
  });
};


The name of the variable where CSRF should be sent and its value are already stored in the global variables, called csrfName and csrfValue respectively.
When the function is run, it fails, returning the classic error: "The action you requested is not allowed."
However, I am correctly passing the variable with the value of the CSRF.


Adding to the LOG file the names and value of the CSRF variables, the COOKIES, POST, BODY, in the file system/Security/Security.php file, we can see that the CSRF is evaluated twice and the first time it is evaluated, it is eliminated from the POST and the COOKIES in the value of the CSRF and therefore when doing the second evaluation, it fails because it does not find the COOKIE with the value of the CSRF
   *** LOG ***
INFO - 2020-12-19 12:26:10 --> CSRF cookie sent
INFO - 2020-12-19 12:26:10 --> Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
INFO - 2020-12-19 12:26:10 --> CSRF cookie sent
INFO - 2020-12-19 12:26:10 --> Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
ERROR - 2020-12-19 12:26:10 -->
-- NEW LOGS ADDED --
CSRFTokenName=t-csrf
CSRFHeaderName=X-CSRF
CSRFCookieName=c-csrf
X-CSRF=f3c1a1fa145e0a4fb5fbc2aaf17a6870
CSRFTokenValue=f3c1a1fa145e0a4fb5fbc2aaf17a6870
Cookies:
array (
  '__utma' => '111872281.366969516.1588867189.1588867189.1588867189.1',
  '_ga' => 'GA1.1.366969516.1588867189',
  '_gcl_au' => '1.1.1182337209.1601045778',
  '_ga_R5V3Y98M6D' => 'GS1.1.1601045778.1.0.1601045778.0',
  '_hjid' => 'dc013f72-0840-401c-9850-b5a19a1e0467',
  '_fbp' => 'fb.0.1601045787964.1964750528',
  'debug-bar-tab' => 'ci-events',
  'c-csrf' => 'f3c1a1fa145e0a4fb5fbc2aaf17a6870',
  'ci_session' => 'qqtk23outqekabjoidjlgkkll7ft9v4v',
  'debug-bar-state' => 'open',
)
BODY:
t-csrf=f3c1a1fa145e0a4fb5fbc2aaf17a6870&data1=value1&data2=value2

POST:
array (
  't-csrf' => 'f3c1a1fa145e0a4fb5fbc2aaf17a6870',
  'data1' => 'value1',
  'data2' => 'value2',
)
-- END of NEW LOGS ADDED --

INFO - 2020-12-19 12:26:10 --> CSRF cookie sent
INFO - 2020-12-19 12:26:10 --> CSRF token verified
ERROR - 2020-12-19 12:26:10 -->
-- NEW LOGS ADDED --
CSRFTokenName=t-csrf
CSRFHeaderName=X-CSRF
CSRFCookieName=c-csrf
X-CSRF=f3c1a1fa145e0a4fb5fbc2aaf17a6870
CSRFTokenValue=f3c1a1fa145e0a4fb5fbc2aaf17a6870
Cookies:
array (
  '__utma' => '111872281.366969516.1588867189.1588867189.1588867189.1',
  '_ga' => 'GA1.1.366969516.1588867189',
  '_gcl_au' => '1.1.1182337209.1601045778',
  '_ga_R5V3Y98M6D' => 'GS1.1.1601045778.1.0.1601045778.0',
  '_hjid' => 'dc013f72-0840-401c-9850-b5a19a1e0467',
  '_fbp' => 'fb.0.1601045787964.1964750528',
  'debug-bar-tab' => 'ci-events',
  'ci_session' => 'qqtk23outqekabjoidjlgkkll7ft9v4v',
  'debug-bar-state' => 'open',
)
BODY:
t-csrf=f3c1a1fa145e0a4fb5fbc2aaf17a6870&data1=value1&data2=value2

POST:
array (
  'data1' => 'value1',
  'data2' => 'value2',
)
-- END of NEW LOGS ADDED --

CRITICAL - 2020-12-19 12:26:10 --> The action you requested is not allowed.
#0 \myPath\\syst\Security\Security.php(235): CodeIgniter\Security\Exceptions\SecurityException::forDisallowedAction()
#1 \myPath\\syst\Filters\CSRF.php(88): CodeIgniter\Security\Security->CSRFVerify(Object(CodeIgniter\HTTP\IncomingRequest))
#2 \myPath\\syst\Filters\Filters.php(173): CodeIgniter\Filters\CSRF->before(Object(CodeIgniter\HTTP\IncomingRequest), NULL)
#3 \myPath\\syst\CodeIgniter.php(382): CodeIgniter\Filters\Filters->run('url...', 'before')
#4 \myPath\\syst\CodeIgniter.php(312): CodeIgniter\CodeIgniter->handleRequest(NULL, Object(Config\Cache), false)
#5 \myPath\\public\index.php(45): CodeIgniter\CodeIgniter->run()
#6 {main}

   *** END of LOG ***

Please can you help me with this?
Reply

#2
SEE:

How to Send AJAX request with CSRF token in CodeIgniter 4

If that doe's not work then you have problems in your coding.
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply

#3
(12-19-2020, 10:43 AM)chirinolopez71 Wrote: My apologies, the problem was that I had the Config/Filter.php file incorrectly configured, it had a double check indicated. Just put something like this:
public $ methods = ['post' => ['csrf']];
Everything else was fine.

--

Hello everyone.
I am new here, but I have already searched and read various things and I cannot find the real and effective solution to my problem.
I have the classic CSRF and AJAX problem, in CodeIgniter 4.0.4. I´m using JQuery 3.5.1 too.


My myFunction() function is automatically executed when the page loads, with JQuery's $ (document) .ready (function () {...})
and it is defined in a .js file, as follows:

var myFunction = function() {
  function onMyFunctionReceived(jsonAnswer) {
     //bla, bla bla
  }
  function onMyFunctionError() {
    //bla, bla bla
  }
  $.ajax({
    url: url,
    data: {[csrfName]: csrfValue, data1: "value1", data2: "value2"},
    type: "POST",
    dataType: "json",
    headers: {[varHdrName]: varValue},
    success: onMyFunctionReceived,
    error: onMyFunctionError
  });
};


The name of the variable where CSRF should be sent and its value are already stored in the global variables, called csrfName and csrfValue respectively.
When the function is run, it fails, returning the classic error: "The action you requested is not allowed."
However, I am correctly passing the variable with the value of the CSRF.


Adding to the LOG file the names and value of the CSRF variables, the COOKIES, POST, BODY, in the file system/Security/Security.php file, we can see that the CSRF is evaluated twice and the first time it is evaluated, it is eliminated from the POST and the COOKIES in the value of the CSRF and therefore when doing the second evaluation, it fails because it does not find the COOKIE with the value of the CSRF
   *** LOG ***
INFO - 2020-12-19 12:26:10 --> CSRF cookie sent
INFO - 2020-12-19 12:26:10 --> Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
INFO - 2020-12-19 12:26:10 --> CSRF cookie sent
INFO - 2020-12-19 12:26:10 --> Session: Class initialized using 'CodeIgniter\Session\Handlers\FileHandler' driver.
ERROR - 2020-12-19 12:26:10 -->
-- NEW LOGS ADDED --
CSRFTokenName=t-csrf
CSRFHeaderName=X-CSRF
CSRFCookieName=c-csrf
X-CSRF=f3c1a1fa145e0a4fb5fbc2aaf17a6870
CSRFTokenValue=f3c1a1fa145e0a4fb5fbc2aaf17a6870
Cookies:
array (
  '__utma' => '111872281.366969516.1588867189.1588867189.1588867189.1',
  '_ga' => 'GA1.1.366969516.1588867189',
  '_gcl_au' => '1.1.1182337209.1601045778',
  '_ga_R5V3Y98M6D' => 'GS1.1.1601045778.1.0.1601045778.0',
  '_hjid' => 'dc013f72-0840-401c-9850-b5a19a1e0467',
  '_fbp' => 'fb.0.1601045787964.1964750528',
  'debug-bar-tab' => 'ci-events',
  'c-csrf' => 'f3c1a1fa145e0a4fb5fbc2aaf17a6870',
  'ci_session' => 'qqtk23outqekabjoidjlgkkll7ft9v4v',
  'debug-bar-state' => 'open',
)
BODY:
t-csrf=f3c1a1fa145e0a4fb5fbc2aaf17a6870&data1=value1&data2=value2

POST:
array (
  't-csrf' => 'f3c1a1fa145e0a4fb5fbc2aaf17a6870',
  'data1' => 'value1',
  'data2' => 'value2',
)
-- END of NEW LOGS ADDED --

INFO - 2020-12-19 12:26:10 --> CSRF cookie sent
INFO - 2020-12-19 12:26:10 --> CSRF token verified
ERROR - 2020-12-19 12:26:10 -->
-- NEW LOGS ADDED --
CSRFTokenName=t-csrf
CSRFHeaderName=X-CSRF
CSRFCookieName=c-csrf
X-CSRF=f3c1a1fa145e0a4fb5fbc2aaf17a6870
CSRFTokenValue=f3c1a1fa145e0a4fb5fbc2aaf17a6870
Cookies:
array (
  '__utma' => '111872281.366969516.1588867189.1588867189.1588867189.1',
  '_ga' => 'GA1.1.366969516.1588867189',
  '_gcl_au' => '1.1.1182337209.1601045778',
  '_ga_R5V3Y98M6D' => 'GS1.1.1601045778.1.0.1601045778.0',
  '_hjid' => 'dc013f72-0840-401c-9850-b5a19a1e0467',
  '_fbp' => 'fb.0.1601045787964.1964750528',
  'debug-bar-tab' => 'ci-events',
  'ci_session' => 'qqtk23outqekabjoidjlgkkll7ft9v4v',
  'debug-bar-state' => 'open',
)
BODY:
t-csrf=f3c1a1fa145e0a4fb5fbc2aaf17a6870&data1=value1&data2=value2

POST:
array (
  'data1' => 'value1',
  'data2' => 'value2',
)
-- END of NEW LOGS ADDED --

CRITICAL - 2020-12-19 12:26:10 --> The action you requested is not allowed.
#0 \myPath\\syst\Security\Security.php(235): CodeIgniter\Security\Exceptions\SecurityException::forDisallowedAction()
#1 \myPath\\syst\Filters\CSRF.php(88): CodeIgniter\Security\Security->CSRFVerify(Object(CodeIgniter\HTTP\IncomingRequest))
#2 \myPath\\syst\Filters\Filters.php(173): CodeIgniter\Filters\CSRF->before(Object(CodeIgniter\HTTP\IncomingRequest), NULL)
#3 \myPath\\syst\CodeIgniter.php(382): CodeIgniter\Filters\Filters->run('url...', 'before')
#4 \myPath\\syst\CodeIgniter.php(312): CodeIgniter\CodeIgniter->handleRequest(NULL, Object(Config\Cache), false)
#5 \myPath\\public\index.php(45): CodeIgniter\CodeIgniter->run()
#6 {main}

   *** END of LOG ***

Please can you help me with this?
Reply

#4
Question 
I'm putting into header, csrf token with filter..

Code:
<?php namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;
use Config\Services;

class CSRFInitFilter implements FilterInterface
{

    /**
    * Do whatever processing this filter needs to do.
    * By default it should not return anything during
    * normal execution. However, when an abnormal state
    * is found, it should return an instance of
    * CodeIgniter\HTTP\Response. If it does, script
    * execution will end and that Response will be
    * sent back to the client, allowing for error pages,
    * redirects, etc.
    *
    * @param RequestInterface $request
    * @param null            $arguments
    *
    * @return mixed
    */
    public function before(RequestInterface $request, $arguments = null)
    {
        // TODO: Implement before() method.
    }

    /**
    * Allows After filters to inspect and modify the response
    * object as needed. This method does not allow any way
    * to stop execution of other after filters, short of
    * throwing an Exception or Error.
    *
    * @param RequestInterface  $request
    * @param ResponseInterface $response
    * @param null              $arguments
    *
    * @return mixed
    */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null): void
    {
// You can check if ($request->isAJAX()), i'll done it through filter,
$response->setHeader(csrf_header(), Services::security()->getCSRFHash());
    }
}


[Filters.php]

Code:
public $filters = [
// Allow only ajax requests
'ajax_request_check' => [
'before' => [
'account/*',
],
'after' => [],
],
'user_smtp_limit' => [
'before' => [
'account/*',
],
'after' => [],
],
'csrf_init_filter' => [
'before' => [],
'after' => [
'account/*',
]];


[app.js]
Code:
$.ajax({
                    url: url,
                    type: 'post',
                    dataType: 'json',
                    data: $('form#' + $(this).attr('id')).serialize(),
                    success: function (data, textStatus, request) {
                        l2.csrf.attr('content', request.getResponseHeader(l2.csrf_header_name));
                        setTimeout(function () {
                            l2.btn_signup.removeAttribute('disabled');
                        }, 7500);
                    },
                    complete: function () {}
                });

If that doe's not work then you have problems in your coding.

realy?
Free Alexey Navalny
Reply


Digg   Delicious   Reddit   Facebook   Twitter   StumbleUpon  


  Theme © 2014 iAndrew  
Powered By MyBB, © 2002-2021 MyBB Group.