REST API 文档

💡 云策文档标注

概述

本文档介绍了WordPress中的Cookie认证方法,包括REST API使用nonce防止CSRF攻击,以及手动Ajax请求中nonce的传递方式。还提到了应用密码和认证插件作为替代方案。

关键要点

  • Cookie认证是WordPress标准认证方法,依赖登录用户的cookies。
  • REST API使用nonce(action设为wp_rest)避免CSRF问题,可通过_wpnonce参数或X-WP-Nonce头传递。
  • 内置Javascript API自动处理nonce,推荐插件和主题开发者使用。
  • 手动Ajax请求需显式传递nonce,否则请求将变为未认证状态。
  • 应用密码(WordPress 5.6+)支持通过Basic Auth进行REST API认证,适用于命令行脚本。
  • 认证插件(如OAuth 1.0a Server、JSON Web Tokens)提供远程应用认证支持。

代码示例

// 生成nonce并本地化脚本
wp_localize_script( 'wp-api', 'wpApiSettings', array(
    'root' => esc_url_raw( rest_url() ),
    'nonce' => wp_create_nonce( 'wp_rest' )
) );

// 在基础模型中设置请求头
options.beforeSend = function(xhr) {
    xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);

    if (beforeSend) {
        return beforeSend.apply(this, arguments);
    }
};

// 使用jQuery AJAX编辑文章标题
$.ajax( {
    url: wpApiSettings.root + 'wp/v2/posts/1',
    method: 'POST',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
    },
    data:{
        'title' : 'Hello Moon'
    }
} ).done( function ( response ) {
    console.log( response );
} );

注意事项

  • Cookie认证仅适用于WordPress内部且用户已登录的情况,用户需具备相应权限。
  • DELETE请求支持有限,建议通过X-WP-Nonce头传递nonce以确保可靠性。
  • 自定义端点无需验证nonce,rest_cookie_check_errors()会自动处理。
  • 应用密码需通过HTTPS使用Basic Auth,适用于安全环境。
  • Basic Authentication插件仅用于开发测试,生产环境推荐使用应用密码。

📄 原文内容

Cookie Authentication

Cookie authentication is the standard authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user.

However, the REST API includes a technique called nonces to avoid CSRF issues. This prevents other sites from forcing you to perform actions without explicitly intending to do so. This requires slightly special handling for the API.

For developers using the built-in Javascript API, this is handled automatically for you. This is the recommended way to use the API for plugins and themes. Custom data models can extend wp.api.models.Base to ensure this is sent correctly for any custom requests.

For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest. These can then be passed to the API via the _wpnonce data parameter (either POST data or in the query for GET requests), or via the X-WP-Nonce header. If no nonce is provided the API will set the current user to 0, turning the request into an unauthenticated request, even if you’re logged into WordPress.

Note: Until recently, most software had spotty support for DELETE requests. For instance, PHP doesn’t transform the request body of a DELETE request into a super global. As such, supplying the nonce as a header is the most reliable approach.

It is important to keep in mind that this authentication method relies on WordPress cookies. As a result this method is only applicable when the REST API is used inside of WordPress and the current user is logged in. In addition, the current user must have the appropriate capability to perform the action being performed.

As an example, this is how the built-in Javascript client creates the nonce:

<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array(
    'root' => esc_url_raw( rest_url() ),
    'nonce' => wp_create_nonce( 'wp_rest' )
) );

This is then used in the base model:

options.beforeSend = function(xhr) {
    xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);

    if (beforeSend) {
        return beforeSend.apply(this, arguments);
    }
};

Here is an example of editing the title of a post, using jQuery AJAX:

$.ajax( {
    url: wpApiSettings.root + 'wp/v2/posts/1',
    method: 'POST',
    beforeSend: function ( xhr ) {
        xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
    },
    data:{
        'title' : 'Hello Moon'
    }
} ).done( function ( response ) {
    console.log( response );
} );

Note that you do not need to verify that the nonce is valid inside your custom end point. This is automatically done for you in rest_cookie_check_errors().

Basic Authentication with Application Passwords

As of 5.6, WordPress has shipped with Application Passwords, which can be generated from an Edit User page (wp-admin -> Users -> Edit User).

The credentials can be passed along to REST API requests served over https:// using Basic Auth / RFC 7617here’s the documentation for how to use it with cURL.

For a simple command-line script example, just swap out USERNAME, PASSWORD, and HOSTNAME in this with their respective values:

curl --user "USERNAME:PASSWORD" https://HOSTNAME/wp-json/wp/v2/users?context=edit

Authentication Plugins

Plugins may be added to support alternative modes of authentication that will work from remote applications. Some example plugins are OAuth 1.0a Server and JSON Web Tokens.

There’s also a Basic Authentication plugin.

Note that this plugin requires sending your username and password with every request, and should only be used for development and testing i.e. not in a production environment. Using Application Passwords (see above) is preferred.