[REST API] How to use Application Passwords in WordPress for REST API Authentication

https://artisansweb.net/how-to-use-application-passwords-in-wordpress-for-rest-api-authentication/

SAJID UPDATED ON JANUARY 5, 2021 LEAVE A COMMENTfacebook sharing button Sharetwitter sharing button Tweetlinkedin sharing button Share

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.

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.

1

add_filter( 'wp_is_application_passwords_available', '__return_true' );

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.

12345

<?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.

Last updated