Raymond Camden
Raymond Camden

Reputation: 10857

Getting 401 trying to create a post even though I'm using an application password

I'm trying to write some basic code that will create a post via Node.js. This is for a WP install hosted by Wordpress.com. I enabled 2FA for the user and made an application password. However, I can't seem to get past:

{
  code: 'rest_cannot_create',
  message: 'Sorry, you are not allowed to create posts as this user.',
  data: { status: 401 }
}

As far as I know, creating the app password should enable simple auth methods to work, but maybe I'm missing something? Here's the code with username/password/host removed:

let username = 'the user name';
let password = '16 digit password';

let auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');

let body = {
 title:'new post', 
  content:'content', 
  status:'draft'
};

let resp = await fetch('https://the site/wp-json/wp/v2/posts', {
  method:'POST',
  headers:{
    'Authorization':auth,
    'Content-Type':'application/json',
  },
  body:JSON.stringify(body)
});
let data = await resp.json();
console.log(data);

Upvotes: 0

Views: 244

Answers (2)

gnasher729
gnasher729

Reputation: 52612

401 means no permission. Never, ever. That is you have a problem that cannot be fixed with correct permissions, unlike 403 which can be fixed by adding permissions.

Upvotes: 0

Scott Z
Scott Z

Reputation: 1155

You are concatenating the word "Basic" twice in the Authorization string.

Once here: let auth = 'Basic ' + Buffer.from(username + ':' + password).toString('base64');

and again here:

'Authorization':'Basic '+auth,

Upvotes: 0

Related Questions