My goal is to send user comments with a POST request from a server-side Lambda function to my WordPress API. I'm using Gatsby and Netlify.
When someone leaves a comment in the comment form of my Gatsby front-end, Netlify receives a form submission event and a Netlify Lambda function gets called. It is in this function that I will prepare and send the comment to my WordPress site through the WP-REST API.
The problem is that my function seems to fail silently. This may be partly due to how Netlify makes available its Functions logs. My hunch was that some form of Authentication was needed to POST a comment to WP REST API so I went ahead and installed the JWT Authentication Plugin (mainly because I believe it is more secure that Basic Auth, though I'm not sure).
I went through the docs for the JWT plugin and made the necessary changes to my .htaccess
and my wp-config.php
file including enabling CORS support and defining a new secret key:
define('JWT_AUTH_SECRET_KEY', 'your-top-secret-key');
In my Lambda function I make a post request the end JWT endpoint:
fetch('https://example.com/wp-json/jwt-auth/v1/token', {
// credentials: 'include',
headers: new Headers({
'Authenticate': 'Basic {what do I put here?}' // Do I need "Basic"?
})
})
.then(response => {
console.log("Did we get a response? ", response)
return response.json()
})
.then(myJson => {
console.log(JSON.stringify(myJson))
})
.catch(error => {
console.log("error: ", error);
throw new Error('Something bad happened.', error)
})
My confusion comes in how to properly set up an Authentication call, if I need to authenticate at all, and whether or not I should be sending my WordPressusername:password
or the JSON Web Token that I defined in my wp-config.php
.
And what should the format of the username/password be? Should it URL-encoded, i.e: username=admin&password=Str0ngPass
or just `username:password'.
This question seems to offer a working approach but I am not using Postman and can't even get a token from my Fetch call. A couple more answers that I found are more theoretical and don't offer much in terms of code examples:
- Using JWT to authenticate a user with an external system?
- Set up Wp Authentication from external API
I also discovered JWT Web Tokens for Node. Maybe I should implement it that way?
I've found the documentation surrounding using fetch to authenticate to be a little patchy. Any help would be greatly appreciated and I'm happy to supply any more code/info that you need.