简体   繁体   中英

CSRF Tokens and Codeigniter 3

I read a lot for CSRF Tokens but I still have few questions.

For example I will demonstrate my situation with codeigniter 3.

I have Login form and make ajax request to /ajax/login

Before send this request i have meta tag with generated csrf token

<meta name="csrf-token" content="<?= $this->security->get_csrf_hash(); ?>">

And

$.ajaxSetup({
                headers: {
                    'X-CSRF-TOKEN':  $('meta[name="csrf-token"]').attr('content')
                }
            });

            $.ajax({
              url: ".../ajax/login",
              context: document.body
            }).done(function() {

            });

Now for my ajax requests token will be added in x-csrf-token header.

Ok token is sent without problems and my "if" statement is

$csrf_ajax = $this->input->get_request_header('X-CSRF-Token', TRUE);
$csrf_cookie = $this->security->get_csrf_hash();

if($csrf_ajax == $csrf_cookie){
    echo "OK";
}else{
    echo 'NOT OK';
}

My Ci config for CSRF is

$config['csrf_protection'] = TRUE;
$config['csrf_token_name'] = 'csrf_protection';
$config['csrf_cookie_name'] = 'csrf';
$config['csrf_expire'] = 3600;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();

After this 3600 Seconds if I repeat same request I will see again "OK". Token still valid but should to be invalid after csrf expire time 3600?

Can you explain me when i can use token per session and token per request? In which cases? In my example why token still valid after this expire time?

The solution that worked for me when user leaves the form for awhile beyond the token expiration time with CSRF enabled for every request is to make a GET request in AJAX Success when request fails because token has expired. Then have a hidden field that continue to be updated with latest token and if at the time of making request it has expired you make a GET REQUEST to fetch latest TOKEN and then evoke click event on function that submits form which means the function has to be passed "this" or ID as part parameter.This makes the user not to realize the process of renewing token in the background

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM