Authenticating WordPress REST API Using JWT Authentication

The WordPress REST API provides a modern way for external applications to interact with WordPress. By default, many REST API endpoints require authentication. While standard cookie-based authentication works for browser-based applications, it’s not suitable for mobile apps or external servers. JSON Web Token (JWT) is a standard method for securely transmitting information between parties as a JSON object, making it ideal for REST API authentication.

This article explains how to set up and use JWT authentication for the WordPress REST API using the JWT Authentication for WP REST API plugin.

Plugin Setup and Configuration

First, install and activate the plugin. Then, you need to add a secret key to your wp-config.php file. You can generate a random string for this:

define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key-here');

You also need to enable CORS support if your frontend application is hosted on a different domain:

define('JWT_AUTH_CORS_ENABLE', true);

Obtaining a Token

Once configured, you can get a token by sending a POST request to /wp-json/jwt-auth/v1/token with your WordPress username and password:

fetch('https://your-site.com/wp-json/jwt-auth/v1/token', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
        username: 'your_username',
        password: 'your_password'
    })
})
.then(res => res.json())
.then(data => console.log(data.token));

Using the Token

After obtaining the token, include it in the Authorization header of your subsequent REST API requests:

fetch('https://your-site.com/wp-json/wp/v2/posts', {
    headers: {
        'Authorization': 'Bearer ' + token
    }
})
.then(res => res.json())
.then(posts => console.log(posts));

By using JWT authentication, you can effectively use WordPress as a headless CMS, developing frontend single-page applications (SPA) that are completely decoupled from the WordPress theme system. This can be a mobile app, a WeChat mini-program, or any web-based application. This article just introduces the method; if you have a better implementation, feel free to share it in the comments!

Related Posts

Leave a Reply

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