Got the following code running on a local wordpress install. I have created an application password for the admin user but am still getting a 401 unauthorised. What am i missing?
Here's the code
jQuery.ajax({
type: "POST",
dataType: "json",
url: '/wp-json/wp/v2/posts',
data: JSON.stringify({
title: me.title(),
content: 'Here is some content',
status: 'published'
}),
beforeSend: function ( xhr ) {
xhr.setRequestHeader('Authorization', 'Basic admin:DqfX r0YT hQE5 lsgu 2Y7d PJv5');
},
success: function (data) {
alert("posted");
},
error: function (error) {
alert("FAILD:" + error);
}
});
Got the following code running on a local wordpress install. I have created an application password for the admin user but am still getting a 401 unauthorised. What am i missing?
Here's the code
jQuery.ajax({
type: "POST",
dataType: "json",
url: 'http://the-lead-magnet-company.local/wp-json/wp/v2/posts',
data: JSON.stringify({
title: me.title(),
content: 'Here is some content',
status: 'published'
}),
beforeSend: function ( xhr ) {
xhr.setRequestHeader('Authorization', 'Basic admin:DqfX r0YT hQE5 lsgu 2Y7d PJv5');
},
success: function (data) {
alert("posted");
},
error: function (error) {
alert("FAILD:" + error);
}
});
Share
Improve this question
asked Jan 24, 2022 at 17:46
CodescriblerCodescribler
1216 bronze badges
7
|
Show 2 more comments
1 Answer
Reset to default 1You should use cookie based authentication instead of basic auth. Delete the basic auth/application password authentication code.
Follow the cookie authentication example that creates a post via the REST API from the REST API handbook:
https://developer.wordpress/rest-api/using-the-rest-api/authentication/#cookie-authentication
- Create a valid nonce for use in your AJAX requests in PHP
wp_create_nonce( 'wp_rest' )
as the docs tell you to - Add a
beforeSend
to your AJAX call like the docs suggest that adds the nonce in a HTTP header:
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', your_nonce_variable );
},
- Make the request while logged into the site from the same domain
the-lead-magnet-company.local
then the use of basic authentication is unnecessary and inappropriate – Tom J Nowell ♦ Commented Jan 24, 2022 at 18:18