Guide to Implementing Authentication Tokens for WordPress API and React Integration

0

Using the WordPress API to fetch data such as login and order information on static pages created with React is very useful. In this article, we will look at how to integrate a React application running on the same server with the WordPress REST API. In particular, we will learn how to set up authentication tokens to securely access data.

1. Understanding the WordPress REST API

WordPress offers a powerful REST API that allows external applications to manage content. Through this API, you can perform CRUD (Create, Read, Update, Delete) operations on posts, pages, users, WooCommerce order information, and more. Understanding the basic structure of the REST API is crucial.

2. Integrating React Application with the API

To fetch data from the WordPress API in a React application, you need to perform API requests directly from the web browser. Let’s look at some important considerations in this process.

Solving CORS Issues

When a React application makes API requests, it needs to solve CORS (Cross-Origin Resource Sharing) issues. You need to properly configure the CORS settings on the WordPress server to allow requests from specific origins.

// Add to the functions.php file in WordPress
function add_cors_http_header(){
    header("Access-Control-Allow-Origin: *");
}
add_action('init','add_cors_http_header');

This code allows requests from all origins. For security reasons, it is better to allow only specific domains.

User Authentication

When API requests require authentication, you can perform authentication using JWT or OAuth. Here, we explain how to authenticate using the JWT method.

Setting up JWT Authentication

  • Install JWT Plugin: Install and activate the JWT Authentication for WP REST API plugin on WordPress.
  • Configure Plugin: Configure the plugin settings by setting the secret key and completing the necessary settings.
// Add to the wp-config.php file in WordPress
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
define('JWT_AUTH_CORS_ENABLE', true);

Issuing Tokens

When a user logs in, you need to issue a JWT token. To do this, use the user login API.

fetch('http://127.0.0.1/wp-json/jwt-auth/v1/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    username: 'your-username',
    password: 'your-password'
  })
})
.then(response => response.json())
.then(data => {
  if (data.token) {
    localStorage.setItem('token', data.token);
  } else {
    console.error('Token not found');
  }
})
.catch(error => console.error('Error:', error));

This code stores the token returned upon successful login in local storage.

Including the Token in API Requests

You need to include the issued token in the `Authorization` header of API requests.

const token = localStorage.getItem('token');

fetch('http://127.0.0.1/wp-json/wp/v2/posts', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  }
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));

This code uses the token stored in local storage to perform authenticated API requests.

3. Integrating API Data in React Components

Within React components, you can fetch API data, store it in state, and display it in the UI.

import React, { useState, useEffect } from 'react';

function UserInfo() {
  const [user, setUser] = useState(null);
  const token = localStorage.getItem('token');

  useEffect(() => {
    fetch('http://127.0.0.1/wp-json/wp/v2/users/me', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'Authorization': `Bearer ${token}`
      }
    })
    .then(response => response.json())
    .then(data => setUser(data))
    .catch(error => console.error('Error:', error));
  }, [token]);

  if (!user) return <div>Loading...</div>;
  return <div>Hello, {user.name}</div>;
}

This component displays the user’s information when they are logged in. The `useEffect` hook performs an API request when the component mounts and stores the response data in state.

Conclusion

Integrating the WordPress API with a React application allows you to create flexible and powerful web applications. This article explained in detail how to fetch data from WordPress in React and set up authentication tokens to securely use the API. Such integration enhances the user experience and provides a wide range of functionalities.

Leave a Reply