Authenticate WordPress REST API Requests with JWT Authentication

WordPress’s standard authentication method is cookie-based. As long as a user is logged into the dashboard, WordPress automatically sets the required authentication cookies. The REST API uses Nonces to avoid CSRF issues, so if we are making REST API requests inside a normal WordPress site, nonce-based authentication is usually enough.

But if we are building a single-page application that runs outside the WordPress theme layer, we cannot rely on WordPress to provide those nonces for us. In that situation, we need another way to authenticate users. A practical approach is to use JWT-based authentication for the WordPress REST API.

Install JWT Authentication for WP REST API to add JWT support to WordPress REST API

WordPress core does not provide JWT authentication out of the box, so we need to install the JWT Authentication for WP REST API plugin to add that server-side capability. You can search for the plugin in the dashboard, install it, and activate it. Before installing it, make sure the WordPress REST API is already enabled, otherwise the plugin will not do anything.

Server requirements for JWT Authentication for WP REST API

  • The minimum PHP version is 5.3.0. Very few hosts still only support PHP 5.3, but that is still the stated minimum.
  • Your host must support the HTTP Authorization header. On many shared hosts this is not enabled by default, so you may need to ask the hosting provider to enable it.

Configure JWT Authentication for WP REST API

JWT needs a secret key to sign tokens. That key should be unique and must never be exposed. The configuration is simple: add a constant to wp-config.php.

define('JWT_AUTH_SECRET_KEY', 'your-top-secrect-key');

You can generate a strong key with the WordPress secret-key service: https://api.wordpress.org/secret-key/1.1/salt/.

Enable CORS support

The JWT Authentication for WP REST API plugin can also help with CORS. If your front-end application and your WordPress site are not on the same domain, you need to allow cross-origin requests. Again, the setup is simple: add another constant in wp-config.php.

define('JWT_AUTH_CORS_ENABLE', true);

Authenticate a user with JWT Authentication for WP REST API

Once the plugin is installed and configured, the REST API gains two additional endpoints:

  • /wp-json/jwt-auth/v1/token: validates a username and password and returns a token.
  • /wp-json/jwt-auth/v1/token/validate: checks whether a token is valid.

The /wp-json/jwt-auth/v1/token endpoint is the entry point we use to validate user credentials. After a successful request, the API returns a token. We then store that token in a cookie or in browser storage for later use. The following example shows a login method from a Vue.js project.

onLogin(formName) {
    this.$refs[formName].validate((valid) => {
        if (valid) {
            HTTP.post('/wp-json/jwt-auth/v1/token', {
                username: this.loginForm.username,
                password: this.loginForm.password,
            }).then(response => {
                this.$store.commit('update', response.data.token);
                Cookie.set('token', response.data.token);
                this.$router.push('/');
            }).catch(e => {
                this.errors.push(e);
            });
        } else {
            console.log('error submit!!');
            return false;
        }
    });
},

In that code, the submitted username and password are sent to /wp-json/jwt-auth/v1/token. After validation succeeds, the returned token is stored in a cookie and the user is redirected to the home page.

Use the JWT token to authenticate later API requests

After we get the token and store it in a cookie, we can attach it to later API requests to prove the user’s identity. The basic idea is to send the token in the Authorization header on every authenticated request.

/**
 * Authenticated HTTP requests
 */
export const HTTP_AUTH = axios.create({
    baseURL         : process.env.baseUrl,
    headers         : {
        'Authorization': 'Bearer ' + Cookie.get('token')
    }
});

The JWT Authentication plugin intercepts each API request, checks the authorization header, decodes the token, validates it, and then returns the appropriate status code and authorization data. For the full list of possible responses, refer to the JWT Authentication for WP REST API plugin page.

With this approach, we can use WordPress as the backend for a front-end application that is completely separate from the WordPress theme system. That application could be a WeChat public-account page, a mini-program, a web-based app, or even a desktop application. This article focuses only on one part of that setup: user authentication outside the theme layer.

Related Posts

Leave a Reply

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