【问题标题】:WordPress check_ajax_referer gives 403 forbidden when using inside AJAX actionWordPress check_ajax_referer 在使用 AJAX 操作时给出 403 禁止
【发布时间】:2018-04-26 04:57:32
【问题描述】:

我正在 WordPress 中进行 AJAX 调用以连接 API。为此,我尝试使用随机数来防止任何未经授权的访问或机器人访问。这是我的代码:

functions.php

add_action('wp_enqueue_scripts', 'yrc_cst_ajax_platform_script_enqueue');

function yrc_cst_ajax_platform_script_enqueue () {
    wp_enqueue_script(
        'platform',
        get_template_directory_uri(). '/includes/platform.js',
        array('jquery'), '1.0', true);

    wp_localize_script('platform', 'yrc_cst_platform', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'ajax_nonce' => wp_create_nonce('platform_security')
    ));
}

add_action('wp_ajax_save_platform_contact', 'yrc_cst_save_platform_contact');

在 AJAX 操作方法中我写了这个(functions.php):

function yrc_cst_save_platform_contact() {
   if ( check_ajax_referer( 'platform_security', $_POST['security'] ) ) {
      var_dump($_POST['security']);
   }
   ...
}

这里是 AJAX 调用:

jQuery.ajax({
   url: yrc_cst_platform.ajax_url,
   type: 'post',
   data: {
      action: 'save_platform_contact',
      security: yrc_cst_platform.ajax_nonce,
      contact_email: client_email
   },
   success: function(response) {
      // Doing my stuff...
   }
});

在控制台中我看到了这个

加载资源失败。服务器响应状态码:403 (禁止)/wp-admin/admin-ajax.php

如果我删除块 check_ajax_referer(...),一切正常。一切都在我的本地。我仅以登录用户身份测试循环。

我不知道如何解决它。

【问题讨论】:

    标签: jquery ajax wordpress nonce


    【解决方案1】:

    尝试使用 wp_verify_nonce 代替 check_ajax_referer,如下所示:

    function yrc_cst_save_platform_contact() {
    if ( wp_verify_nonce( $_POST['security'], 'platform_security' ) ) {
      var_dump($_POST['security']);
    }
     ...
    }
    

    【讨论】:

      【解决方案2】:

      check_ajax_referer 的第二个参数用于指定在 $_REQUEST 中查找 nonce 的位置。当您调用 check_ajax_referer( 'platform_security', $_POST['security'] ) 时,您基本上会告诉函数检查 $_REQUEST[$_POST['security']]。

      你应该这样使用它:

      check_ajax_referer( 'platform_security', 'security' )
      

      您可以在此处阅读更多信息:https://codex.wordpress.org/Function_Reference/check_ajax_referer

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-05
        • 2019-04-10
        相关资源
        最近更新 更多