How to use Application Passwords in WordPress for REST API Authentication

As a WordPress developer, you must be aware of the REST API in WordPress. WordPress provides an interface(REST API) to interact with WordPress from your application. These applications can be anything on the frontend like React, Angular, other PHP applications.

The interaction between your application and WordPress communicates through HTTP requests. You have to send an HTTP request to the WordPress endpoint. And to protect your applications, all these requests should come from valid resources. No one should publicly give a call to the WordPress endpoint. In order to protect the API call, WordPress accepts a unique token in the authorization header. WordPress validates this token and processes the request accordingly.

WordPress 5.6 introduced a new feature ‘Application Passwords’. It basically allows you to create a token from the WordPress dashboard which then can be used in the authorization header.

In this article, we study how to use application passwords with WordPress REST API. We will write the example code for REST API in cURL, Guzzle, and jQuery.

Generate Application Passwords in WordPress

WordPress 5.6 by default adds the section ‘Application Password’ under the Users->Profile page. This feature is available to all sites served over SSL/HTTPS. If your site is not on HTTPS then you can make this feature enabled using the below filter.

add_filter( 'wp_is_application_passwords_available', '__return_true' );

Head over to the Users->Profile page and generate the password by providing an Application Name. WordPress then produces a password which you can use in your frontend application for HTTP requests. Though WordPress gives you a password with spaces, you can use this password with or without spaces. WordPress strips out the spaces at their end.

application-password

You got your application password. Now, you have to generate a valid token for the authorization header. A valid token is a combination of your WordPress site username and application password in base64 encoded format. The user can generate it easily as follows.

<?php
$username = 'admin'; // site username
$application_password = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';
 
echo base64_encode($username.':'.$application_password);

In the above code, I passed the ‘admin’ username and my own application password. Adjust these values as per your credentials. Finally, you will get the base64 encoded version of a valid token. Now, let’s see how to call WordPress REST API using this token.

Calling WordPress REST API

WordPress gives several endpoints that will receive API requests from your application. Go through the list of available endpoints in WordPress. Apart from these available endpoints, you can also add your own custom endpoints in WordPress.

For the sake of the tutorial, I take an example of the Posts endpoint of creating a post. To create a post in WordPress, you have to send POST requests with parameters on this endpoint SITE_URL/wp-json/wp/v2/posts.

Now, let’s see how to call this endpoint using cURL, Guzzle, and jQuery. On the basis of your application, you can take a reference from any of the options below.

WordPress REST API using PHP cURL

You might build your application in PHP. The user can interact with WordPress from their PHP application using cURL and Guzzle. In the case of cURL, make sure the cURL extension is enabled on your server. After this, you can use the below code which will create the post in WordPress.

<?php
$username = 'admin';
$application_password = 'MGOw EG9V 04xo sUZ0 60wo J2OG';

$url = 'SITE_URL/wp-json/wp/v2/posts';
 
$json = json_encode([
    'title' => 'Post using REST API',
    'content' => 'Post content using REST API',
    'status' => 'publish',
]);

try {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, $username.':'.$application_password);
    curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $json);
    $result = curl_exec($ch);
    $status_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    print_r(json_decode($result));
} catch(Exception $e) {
    echo $e->getMessage();
}

Make sure to replace the values of username, application password, and SITE_URL with your actual values. Run this code and your post will be created in the WordPress dashboard.

WordPress REST API using Guzzle in PHP

Guzzle is an alternative to cURL. It’s a PHP HTTP client that makes it easy to send HTTP requests and trivial to integrate with REST APIs. Install the Guzzle library using the command:

composer require guzzlehttp/guzzle

Next, your code to create a post using WordPress REST API and Guzzle will be as follows.

<?php
require_once "vendor/autoload.php";
 
use GuzzleHttp\Client;

$username = 'admin';
$application_password = 'MGOw EG9V 04xo sUZ0 60wo J2OG';

try {
    $client = new Client([
        // Base URI is used with relative requests
        'base_uri' => 'SITE_URL',
    ]);
    
    $response = $client->request('POST', '/wp-json/wp/v2/posts', [
        'json' => [
            'title' => 'Post using REST API',
            'content' => 'Post content using REST API',
            'status' => 'publish',
        ],
        "headers" => [
            "Authorization" => "Basic ". base64_encode($username.':'.$application_password)
        ],
    ]);

    $body = $response->getBody();
    $arr_body = json_decode($body);
    print_r($arr_body);
} catch(Exception $e) {
    echo $e->getMessage();
}

Here, I am using the base64_encode() function of PHP for encoding the string. In the case of cURL, we didn’t need to do it explicitly. The cURL encodes the string on its own.

WordPress REST API using jQuery

When it comes to jQuery, we normally give an API call when a specific event fires. This event can be anything like click, change, load, etc. I am not writing about any event. Instead, I write the code directly which you can wrap up inside your events.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js" integrity="sha512-bLT0Qm9VnAYZDflyKcBaQ2gg0hSYNQrJ8RilYldYQ1FxQYoCLtUjuuRuZo+fjqhx/qtq/1itJ0C2ejDxltZVFg==" crossorigin="anonymous"></script>
<script>
jQuery(function($) {
    var username = 'admin';
    var application_password = 'MGOw EG9V 04xo sUZ0 60wo J2OG';
    $.ajax({
        type: 'POST',
        url: 'SITE_URL/wp-json/wp/v2/posts',
        beforeSend: function(xhr) {
            token = btoa(username + ':' + application_password)
            xhr.setRequestHeader('Authorization', 'Basic ' + token);
        },
        data: {
            'title': 'Post using REST API',
            'content': 'Post content using REST API',
            'status': 'publish'
        },
        success:function(response) {
            console.log(response);
        }
    });
});
</script>

In the above code, I am using the method btoa. The btoa() method encodes a string in base-64. You can also see the API response in your browser console.

I hope you may learn to use application passwords in WordPress with your application. I would like to hear your thoughts and suggestions in the comment section below.

Related Articles

If you liked this article, then please subscribe to our YouTube Channel for video tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *