New CSRF Ajax Header with each Reload

New CSRF Ajax Header with each Reload

blabablabablabablaba Posts: 47Questions: 19Answers: 0

Hi Allan,

My app uses CSRF tokens. Upon the execution of GET or POST actions, the CSRF token is used and refreshed / returned int he response. The app save the new token.

I have a datatable which incorporates a token as follows:

function dtVars(agia,row_ID) {

    $('#admin-form').html($('#admin-form-vars').render(data));

    if($('#admin-form').css('display') != 'block'){
        $("#admin-form").slideToggle();
    }

    $('#admin-dt').DataTable( {
        dom: "Bfrtip",
        ajax: {
            headers: {
                'CSRFToken': csrf
            },
            data: {
                agia: 14,
                agia_x: agia
            },
            dataType: 'json',
            type: 'get',

...

        buttons: [
            {
                text: 'Reload',
                action: function ( e, dt, node, config ) {
                    dt.ajax.reload();  // OPTION 1 - DOESN'T WORK WITH RELOAD
//                    dtVars(14);        // OPTION 2 - WORKS WITH RELOAD
                }
            }
        ]

}

Using OPTION 1; dt.ajax.reload() the CSRF token does not update causing the request to fail.

My workaround OPTION 2; wraps the table in a function dtVars(). On reload button click, the function is called and the entire table is re-initialised. This may not be the most efficient way - ?

I have consulted the useful information here: https://editor.datatables.net/manual/security#Prevention . I separately tried to change .ajaxSetup - but this also does not allow the CSRFHeader to be set dynamically.

Can you confirm: Is OPTION 2 perfectly acceptable? Is there a better way I should approach this? It would be most ideal if the CSRFtoken could be dynamicaly changed in the header and the data reloaded without reinitialising the entire table.

I look forward to your response.

Steve

This question has an accepted answers - jump to answer

Answers

  • blabablabablabablaba Posts: 47Questions: 19Answers: 0

    Hi Allan,

    I will not use a CSRFToken for GET requests. Therefore, I should be able to use dt.ajax.reload()

    Sorry for any inconvenience :-)

    Steve

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Hi Steve,

    Thanks for posting back. Although you've got a workaround, just for completeness in jQuery's ajax method (which is basically what DataTables is using) there is a beforeSend function that can be used to add headers (while the headers option appears to be static). This SO post shows how it might be done.

    Allan

This discussion has been closed.