11 Aug

Enabling JWT Authentication on WordPress

There are lots of reasons a developer might have for Enabling JWT Authentication for their WordPress instance. Perhaps you are doing some automated migration, or maybe you are building an app that uses WordPress as a back-end with some other technology on the front-end, such as Vue or React. Whatever you might need JWT for, it’s a pretty simple process to enable. After enabling JWT authentication, you will be able to authenticate via scripts or other code bases to add, update, read, and delete data as you please.

Step 1: Modify Your .htaccess file

This step requires modification to the WordPress files. So beware if you aren’t familiar with this. This file is read by Apache, and it can make all sorts of things go wrong if you aren’t careful. Go ahead and add the following lines of code between the IfModule tags:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]

This code allows HTTP Authorization headers, which are disabled by WordPress out of the box.

Step 2: Install the JWT Authentication Plugin

After trying a few solutions, this plugin by Enrique Chavez ended up being the one that worked best. It has a few drawbacks in certain situations, but it was perfect for us. Notably, if you are using basic auth for your site, this plugin won’t work simply for you. There seem to be a few workarounds, but I haven’t tested them.

Log in to your WP admin page and go to Plugins. Search for JWT, and the first result should JWT Authentication for WP REST API. This is the one we want.

Step 3: Authenticate with JWT

With those steps out of the way, you can use whatever code language you want to authenticate with JWT. I have done this with Python and Javascript, both of which worked just fine. If you are interested in seeing an example of WordPress authentication with Node.js, check out this article.

11 Aug

GitHub for WordPress Site Deployment

If you haven’t used Git before, it can feel overwhelming to implement and understand how you might use GitHub for WordPress. I’m confident that you will have a decent understanding of how to implement and operate Git in a WordPress project by the end of this article.

Let’s start by thinking of Git as a place to store code online. It also provides a way of adding to the code, accessing the code, and so on. It also maintains a thorough history of every change/commit made to the code base. Git is an extremely powerful development tool. It can be used to create parallel branches of code for testing new features. This allows experimental work without impacting the functioning version. Code changes can be implemented, tested, then reverted or thrown out if it isn’t working out. It allows code to exist in multiple locations while keeping all of them in sync. This is merely the tip of the iceberg. The rest requires a much deeper dive.

Most developers I know use Git from the command-line. If that is too foreign to you, there are some fantastic GUI systems available that can help achieve the goal. I’ll focus on the command-line here, but all the concepts apply the same to a GUI version.

Typically WordPress code lives two places: on the local development machine and the web server. Code and files can be updated via FTP or some other method. Using GitHub for WordPress, the WordPress code will exist in 3 places. There will be a local copy for development, a copy on your web server, and the master version in GitHub.

Step One

Go to GitHub and get an account if you don’t have one. It’s 100% free, by the way. They even let you have private repositories at no cost. Thank you, Microsoft.

Step Two

Create a repository. Give it a unique name, and a description if you can. Make it private too. Once you complete this step, you will be provided a URL link to your repository. Copy this, we will use it in the next step.

Step Three

Turn the wp-content folder into a git enabled directory and add the remote repository address. Essentially, this step is informing our wp-content folder where to send data for storage and versioning. This is fairly simple if you have SSH access to your server. On your web server, use the following commands to get it done:

  1. cd ~/var/www/<your site>/wp-content
  2. sudo git init
  3. sudo git remote add origin <the link you copied in step two>

Step Four

Now we need to add the wp-content folder to our Git repository and upload the data. While we are still in the wp-content folder root, do the following:

  1. sudo git add .
  2. sudo git commit -m ‘init commit’
  3. sudo git push origin master

That’s it! Now you can access your code in the repository from anywhere. To copy the code locally, navigate to the root of your local WordPress project and remove the wp-content folder, then pull down the code. Use the following to do so:

  1. cd path/to/your/local/env/root
  2. rm -rf wp-content
  3. git clone <link to your repo> wp-content
11 Aug

WordPress REST Authentication with Node

Wordpress REST Authentication

No matter what type of automation you are trying to add to your WordPress instance, it always starts with authentication. In my research, I found that there are a few ways to accomplish this within Node.js. Authenticating with WordPress REST was my goal, and using JWT seemed the logical way to do it. This npm package worked well. You will also need to enable the WordPress instance. This package adds robust WordPress REST routes and works like a charm.

Step 1: Enable HTTP Authorization Headers in .htaccess

Add the following to the .htaccess file between the IfModule tags:

RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) – [E=HTTP_AUTHORIZATION:%1]

Note: If you are using something like WP Engine, you will have some additional configuration.

Step 2: Install the JWT Plugin and Activate it

Go to your WordPress admin screen, then Plugins. A quick search for JWT should bring it up as the first choice: JWT Authentication for WP REST API. Enrique Chavez is the creator.

Step 3: Create a Reusable JS WordPress REST Authentication Library

You will need an HTTP agent such as Axios, SuperAgent, or Request. I used Axios here.

// WP.js
// imports
const axios = require(‘axios’);
const WPAPI = require(‘wpapi’);

// constants
const BASE_URL = ‘https://somewordpresssite.com’;
const WP_USER = ‘wp-admin’;
const WP_PASS = ‘password’;

// init
const init = async () => {
try {
  const authURL = `${BASE_URL}/jwt-auth/v1/token`;
  const wp = new WPAPI({ endpoint: BASE_URL });

  // make a post request to get a new token
  const result = await axios.post(authURL, {
    username: WP_USER,
    password: WP_PASS,
  });

  // destructure the token from the result
  const { data: { token } } = result;

  // set the Authorization header with the bearer token
  wp.setHeaders(‘Authorization’, `Bearer ${token}`);

  // await the user data and assign it to the wp object
  await wp.users().me();

  // return the wp object
  return wp;
} catch (e) {
  // some basic error handling
  console.error(‘Unable to authenticate with WordPress’, e.message);
  throw new Error(e);
}
};

module.exports = { init };

Step 4 – Authenticate with WordPress REST and Fetch Some Data

const { init } = require(‘./WP’);

(async () => {
const wp = await init();

const allCats = await wp.categories();
console.log(allCats);
})();