In the introductory part of this series, we took a quick review of REST architecture and how it helps us create better applications. We then explored the history of REST APIs in WordPress and introduced ourselves to the latest addition: the WP REST API plugin. We set up a basic working environment for testing the plugin, which includes the plugin installation and an HTTP client for sending requests or viewing server responses.
In the current part of this series, we will set up a basic authentication protocol on the server to send authenticated requests to perform various tasks through the REST API.
Specifically, in this section we will:
- View the various authentication methods available when using the REST API plugin
- Set up basic authentication on the server
- Using Postman to send authenticated requests
- Sending authenticated requests using a JavaScript framework
- Sending authenticated requests using the command line
- Sending authenticated requests using the WP HTTP API
But let's first look at the authentication itself.
What is authentication?
At its most basic definition, identity verification is the process of determining an individual’s identity.
According to Internet Encyclopedia:
The process of identifying an individual, usually based on a username and password. In security systems, authentication differs from authorization, which is the process of granting access to system objects to an individual based on their identity. Authentication only ensures that an individual is who he or she claims to be, but does not specify the individual's access rights.
Talking about the WP REST API, a user with sufficient permissions can perform various CRUD tasks such as creating a post, retrieving all users of the site, or revoking a user's permissions. But for all these operations, the user must prove his/her identity to the server, and this is where authentication comes into play.
Without proper authentication, it is easy for someone with mischievous ambitions to compromise a website, so authentication provides the necessary layer of security to limit a user's permissions and actions they can perform.
Authentication using WP REST API
WP REST API provides three authentication options, each with a specific purpose. The options are:
- Basic Authentication
- OAuth Authentication
- cookie authentication
Currently, the native way to authenticate with WordPress is through cookie authentication. This is how WordPress determines who a user is and what actions they can perform. To use the other two authentication methods listed above with the WP REST API, we need to install the corresponding plugins provided by the WP REST API team on GitHub. Hopefully, both methods will also be included in WordPress core via the REST API plugin itself.
Basic authentication is the most basic type of HTTP authentication, where login credentials are sent along with the request headers.
How basic authentication works
In basic authentication, the client requests a URL that requires authentication. The server requests the client (or user agent) to authenticate itself by sending the 401-Not Authorized code. In return, the client sends back the same request, but with the login credentials as a Base64-encoded string in the format username:password
. The string is sent in the Authorization
header field as follows:
Authorization: Basic {base64_encode(username:password)}
So if the username is tutsplus
and the password is 123456
, the following header fields will be sent with the request:
Authorization: Basic dHV0c3BsdXM6MTIzNDU2
Since base64 encoded strings can be easily decoded, this method is very unsafe to use on open networks. Therefore, this method can only be used for debugging and development purposes when the connection between server and client is trusted.
Install plug-in
As mentioned above, the WP REST API team provides the plugin on GitHub. So, all we need to do is clone it into the plugins
directory and activate it.
Go to your /wp-content/plugins/
directory and clone the plugin you may need sudo
permissions to run commands. To do this, issue the following command:
$ sudo git clone https://github.com/WP-API/Basic-Auth.git
The terminal will ask you to enter your password. Enter your password and clone the repository into a directory.
After cloning the plugin, activate it through WP Administrator. Basic HTTP authentication methods can now be used with the REST API plugin.
Using Postman to send authenticated requests
Most HTTP clients natively support sending requests using the basic authentication method, as does Postman for Chrome. To send an authenticated request, go to the Authorization tab below the address bar:
现在从下拉菜单中选择基本身份验证。系统将要求您输入用户名和密码。输入您的凭据后,点击更新请求按钮。
更新身份验证选项后,您将在标头选项卡中看到更改,并且现在包括一个标头字段,其中包含编码的用户名和密码字符串:
这就是我们如何使用 Postman 设置基本身份验证。现在您可以发送测试请求,例如删除帖子,这需要身份验证:
DELETE http://dev-server/wp-json/wp/v2/posts/52
其中 dev-server
是您的开发服务器的路径。
如果一切顺利,服务器将返回200 OK状态代码,表明id为52
的帖子已被删除:
不用担心我们在这里提出的请求 - 我们将在以后的部分中更详细地讨论它该系列。
从命令行发送经过身份验证的请求
我们可以使用命令行使用此方法发送经过身份验证的请求。考虑以下与上述请求等效的 curl
:
curl --request DELETE -I --user admin:password http://dev-server/wp-json/wp/v2/posts/52
服务器将发送以下响应,表明一切正常:
HTTP/1.1 200 OK Date: Fri, 28 Aug 2015 20:02:43 GMT Server: Apache/2.4.6 (CentOS) PHP/5.6.12 X-Powered-By: PHP/5.6.12 Set-Cookie: PHPSESSID=k0rg6mcbsie7ufvoav219lqre0; path=/ Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache X-Content-Type-Options: nosniff Link: <http://localserver/wordpress-api/demo-post-28/>; rel="alternate"; type=text/html Allow: GET, POST, PUT, PATCH, DELETE Transfer-Encoding: chunked Content-Type: application/json; charset=UTF-8
--request
选项指定要使用的请求方法,在我们的示例中为 DELETE
。您还可以使用 -X
作为 --request
选项的替代选项。
-I
选项仅获取服务器发送的 HTTP 标头。 -I
的替代选项是 --head
选项。
使用 JavaScript 发送经过身份验证的请求
如果您使用客户端 JavaScript 框架(例如 jQuery)与启用了 WP API 的 WordPress 站点进行远程交互,则可以在 AJAX 请求中发送授权标头。考虑通过 jQuery.ajax()
方法发送的以下 DELETE
请求:
$.ajax({ url: 'http://dev-server/wp-json/wp/v2/posts/52', method: 'DELETE', crossDomain: true, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'Authorization', 'Basic ' + Base64.encode( 'username:password' ) ); }, success: function( data, txtStatus, xhr ) { console.log( data ); console.log( xhr.status ); } });
其中 Base64
是用于编码和解码 Base64 字符串的对象。在上面的 jQuery.ajax()
方法调用之前,其定义如下:
var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/\r\n/g,"\n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}};
我在 StackOverflow 上找到了它,它是一种在 JavaScript 中编码和解码 Base64 字符串的跨浏览器方式。
在上述请求中,我们使用 xhr
对象的 setRequestHeader()
方法作为参数传递给 Authorization
标头beforeSend()
方法。
除了上述请求之外,Access-Control-Allow-Headers
标头还应允许服务器上的 Authorization
字段。可以通过在 WordPress .htaccess 文件中添加以下代码行来启用此功能:
Header always set Access-Control-Allow-Headers Authorization Header always set
上述请求完成后,将在浏览器控制台中回显响应,如下图所示:
服务器返回的200状态响应代码显示id为52
已成功删除。
使用 WP HTTP API 发送经过身份验证的请求
如果您通过 WordPress 安装与另一个 WordPress 站点进行远程交互,发送 HTTP 请求的最合适方法是 WP HTTP API。
考虑以下代码,该代码将 DELETE
请求发送到另一个启用了 WP REST API 和基本身份验证的 WordPress 安装:
$wp_request_headers = array( 'Authorization' => 'Basic ' . base64_encode( 'username:password' ) ); $wp_request_url = 'http://localserver/wordpress-api/wp-json/wp/v2/posts/52'; $wp_delete_post_response = wp_remote_request( $wp_request_url, array( 'method' => 'DELETE', 'headers' => $wp_request_headers ) ); echo wp_remote_retrieve_response_code( $wp_delete_post_response ) . ' ' . wp_remote_retrieve_response_message( $wp_delete_post_response );
这里我们使用了 wp_remote_request()
函数,它接受两个参数:
-
$url
: 请求的URL -
$args
:要传递的附加参数数组
$args
数组中定义的 $method
数组是 DELETE
,并且应始终以大写形式书写。 $headers
数组采用随请求传递的所有标头字段的键值对。我们已经传递了 Authorization
密钥,其值为 base64 编码的用户名和密码字符串。
响应将保存在 $wp_delete_post_response
变量中,我们可以将其与 wp_remote_retrieve_response_code()
和 wp_remote_retrieve_response_message()
一起使用功能。这两个函数是 WP HTTP API 中的辅助函数,它们分别从响应中提取状态代码和状态消息。
如果通过上述请求成功删除帖子,则会回显以下文本:
200 OK
这就是 WP REST API 支持的基本身份验证方法。由于其简单性,除非另有说明,我们将在未来的部分中使用相同的身份验证方法来检索、创建或修改数据。
结论
在本系列的当前部分中,我们仔细研究了 WP REST API 支持的基本 HTTP 身份验证方法。但是,它不应该在实时生产环境中使用,因为 Base64 编码的字符串很容易被解码,并且您的凭据可能会落入坏人之手。
成功设置并测试 HTTP 基本身份验证方法后,我们准备进一步设置更复杂的身份验证方式 — OAuth 1.0a 方法。我们将在本系列的下一部分中做到这一点,敬请期待!
The above is the detailed content of Set up and use WP REST API with Basic Authentication. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version
Useful JavaScript development tools