Ajax inside wordpress security

Before I get to the question, let me explain how we have things set up.

We have a proxy.php file, in which class Proxy is defined with functions that call upon a rest for creating/editing/getting WordPress posts, fields etc.

Read More

Then, we have a proxyhandler.php, in which Proxy class is initialized and serves as a handle between proxy.php and a javascript file.

In javascript file we have an ajax call to proxyhandler.php in which we send our secret and other data.

Now, the problem arises here:
We define the secret through wp_localize_script, by using md5 custom string + timestamp. We send the encripted string and timestamp through ajax to proxy handler, where we use the previous (hardcoded inside proxyhandler) string and timestamp to generate a md5 string again, and check the one sent against the one generated. If they are the same, we continue by doing whatever was requested, if they dont fit, we just return that the secret didn’t match.

Now, the real issue comes here – by using wp_localize_script, the variable for the secret is global and as such, anyone can utilize it via dev tools and can send any ajax request to proxyhandler that they want.

What would be the proper procedure to make it more secure? We’ve thought of doing this:
Instead of using wp_localize_script, we put the script inside a php file, we define the secret using a php variable and then simply echo the secret file into ajax. Would this be viable, or are there any other ways?

Related posts

Leave a Reply

1 comment

  1. Instead of sending an encrypted string in global scope, then check against it, you should use nonce in your AJAX request:

    var data = {
        action: 'your_action',
        whatever_data: who_know,
        _ajax_nonce: <?= wp_create_nonce('your_ajax_nonce') ?>
    };
    

    Then, use check_ajax_refer() to verify that nonce:

    function your_callback_function()
    {
        // Make sure to verify nonce
        check_ajax_refer('your_ajax_nonce');
    
        // If logged in user, make sure to check capabilities.
        if ( current_user_can($capability) ) {
            // Process data.
        } else {
            // Do something else.
        }
        ...
    }
    

    Depend on the AJAX METHOD, you can use $_METHOD['whatever_data'] to retrieve who_know data without needing to use wp_localize_script().

    Also remember that we can allow only logged in users process AJAX data:

    // For logged in users
    add_action('wp_ajax_your_action', 'your_callback_function');
    
    // Remove for none logged in users
    // add_action('wp_ajax_nopriv_your_action', 'your_callback_function');
    

    The final thing is to make sure NONCE_KEY and NONCE_SALT in your wp-config.php are secure.