How to use Application Passwords in WordPress for REST API Authentication

As a developer, you must be aware of the REST API in WordPress. WordPress provides a REST API to interact with the WordPress websites from your application. These applications can be anything like React, Angular, WordPress, or other PHP applications.

The interaction between your application and WordPress happened over HTTP requests. You need to send an HTTP request to the REST API URLs. It’s the developer’s responsibility to check all these requests coming from valid sources. No one should publicly give a call to these endpoints. To protect the REST API endpoints, WordPress accepts a unique token in the Authorization header. WordPress validates this token and processes the request only if a token is valid.

Starting with WordPress 5.6, the software introduced a new feature called Application Passwords. With the combination of the WordPress username and this application password, we create a token that can be used in the Authorization header.

Having said that, let’s study how to use application passwords with WordPress REST API. We will write the example code for REST API in cURL, Guzzle, and JavaScript.

Generate Application Passwords in WordPress

You’ll find the Application Password under the Users->Profile page. This feature is available to all sites served over SSL/HTTPS. Just in case, if you are on the staging server which is not on HTTPS, you can enable Application Password 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. Though WordPress gives you an application password with spaces, you can use this password with or without spaces to create a unique token.

application-password

Once you get your application password, you have to generate a valid token. This token is a combination of your WordPress website’s username and application password in base64 encoded format. The user can easily generate it 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 string of a valid token. Now, let’s see how to call WordPress REST API using this token.

Calling WordPress REST API

WordPress gives different endpoints to receive API requests from your application. Here is a list of available endpoints in WordPress. Apart from these 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 for creating a post. To create a post in WordPress, you have to send POST requests to this endpoint SITE_URL/wp-json/wp/v2/posts.

If you are curious about how to use this endpoint from WordPress itself, then the below code will give you an idea.

<?php
$username = 'admin';
$application_password = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';

$request = wp_remote_post(
	"SITE_URL/wp-json/wp/v2/posts",
	array(
		'headers' => array(
			'Authorization' => "BASIC ". base64_encode($username.':'.$application_password)
		),
		'body' => array(
			'title' => 'Post using REST API',
            'content' => 'Post content using REST API',
            'status' => 'publish',
		)
	)
);

if( 'Created' === wp_remote_retrieve_response_message( $request ) ) {
	$post = json_decode( wp_remote_retrieve_body( $request ) );
	print_r($post);
}

In the next section, we’ll call this endpoint using cURL, Guzzle, and JavaScript. On the basis of your application, you can take a reference from any of the options.

WordPress REST API using PHP cURL

You might be building your application in PHP. Using cURL and Guzzle, you can interact with WordPress from your PHP application. To use cURL, make sure the cURL extension is enabled on your server. The below code written using cURL will create the post in WordPress.

<?php
$username = 'admin';
$application_password = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';

$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. Before use, you have to install it 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 = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';

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 cURL example, we don’t need to do it explicitly. The cURL encodes the string on its own.

WordPress REST API using JavaScript

Similar to PHP, you may wish to interact with WordPress REST API with JavaScript. It can be done using Fetch API which provides a JavaScript interface to send HTTP requests and receives a response.

<script>
var username = 'admin';
var application_password = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';
    
fetch("SITE_URL/wp-json/wp/v2/posts", {
    method: "POST",
    headers: {
        "Authorization": "Basic " + btoa(username + ':' + application_password),
        "Content-Type": "application/json",
    },
    body: JSON.stringify({
        "title": "Post using REST API",
        "content": "Post content using REST API",
        "status": "publish"
    }),
})
.then(response => response.json())
.then(data => {
    console.log(data);
});
</script>

In this JavaScript code, I use btoa() method to encode a base-64 string. I am doing this just for demo purposes. You should pass these credentials securely. You may pass it via the environment variable.

WordPress REST API using jQuery

People who want to achieve the same goal with jQuery can use the following code.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script>
jQuery(function($) {
    var username = 'admin';
    var application_password = 'Ho9c 9vGs AOBG nXb0 FPpr W5vO';
    $.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>

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.

11 thoughts on “How to use Application Passwords in WordPress for REST API Authentication

  1. You wrote:
    > Just in case, if you are on the staging server which is not on HTTPS, you can enable Application Password using the below filter.

    > add_filter( ‘wp_is_application_passwords_available’, ‘__return_true’ );

    However, this only unlocks the GUI; the generation of passwords still fails.
    The right way (at least in WP 6.4.1) is to set the environment variable WP_ENVIRONMENT_TYPE to ‘local’ (without quotes), and you’re good to go.

  2. For those having trouble, and the following error message :
    “Sorry, you are not allowed to create new posts.”

    You should add the following in your .htaccess file :
    # BEGIN WP BASIC Auth

    RewriteEngine On
    RewriteBase /
    RewriteCond %{HTTP:Authorization} ^(.*)
    RewriteRule .* – [e=HTTP_AUTHORIZATION:%1]
    SetEnvIf Authorization “(.*)” HTTP_AUTHORIZATION=$1

    # END WP BASIC Auth

    Cheers !

  3. Hello Sajid,

    Very interesting article.
    However I get the message “Sorry, you are not allowed to create new posts.”
    My user has admin rights, so it should not be a problem.
    And of course, I changed the application password and site name.

    Any idea ?

  4. What? using application_password in JS? That is not safe!
    Everybody who uses your website can see your password if it is pasted somewhere in JS.
    Instead you need to make call to you back-end and use your application_password there.

    1. You’re right. One should not paste a password in JS. Instead using an environment variable is recommended.

      The token must come from the client end then only the backend can find it it’s from a valid source.

  5. In case I’m using jQuery, do I have to localize the script? I feel like I’m missing 1 step…

    1. If you are calling API endpoint from WordPress then localize it. Here, I just wrote plain JS because users outside WordPress also deals with API.

Leave a Reply

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