Headless WordPress: How to authenticate front end requests?

I am envisioning WordPress on the back end to work with React.js on the front end like this:

  1. WordPress is installed on http://example.com/api
  2. React.js script is loaded into http://example.com/index.html, through script tags and then injected into a root div

There is a problem though. Without wordpress controlling registration and enqueuing, I do not see how to localize a nonce into the React.js script file.

Without the nonce the routes would not be authenticatable as cookie verification requires it in the X-WP-Nonce header. https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/

An API request could be made for a nonce, but the route would necessarily be unprotected, making it highly insecure.

What is the solution to this? How are you guys setting up headless wordpress to pass authentication information, such as a nonce, to your front end script files?

1 Answer
1

The nonce authentication method is only for requests made from within WordPress, as described in your own link (emphasis mine):

It is important to keep in mind that this authentication method relies
on WordPress cookies. As a result this method is only applicable
when the REST API is used inside of WordPress and the current user is
logged in.
In addition, the current user must have the appropriate
capability to perform the action being performed.

Your link then describes some other methods that are available for remote requests:

While cookie authentication is the only authentication mechanism
available natively within WordPress, plugins may be added to support
alternative modes of authentication that will work from remote
applications. Some example plugins are OAuth 1.0a Server, Application
Passwords, and JSON Web Tokens.

If you’re making authenticated requests from a React application outside of WordPress, you need to use one of those methods.

Leave a Comment