damix911
damix911

Reputation: 4443

jQuery, HTTPS and WooCommerce API: Error 401

I am trying to use Basic Auth over HTTPS to invoke the WooCommerce API, from same-origin (localhost), with jQuery. The server is XAMPP on Windows. I am using a self-signed certificate (with CN=localhost). The certificate issues no warnings when I visit the rest of the website. I tried adding the certificate as Trusted Root Certification Authority. I even allowed chrome://flags/#allow-insecure-localhost (even though the certificate is valid). I keep getting "401 Unauthorized".

var username = "ck_????????????????????????????????????????";
var password = "cs_????????????????????????????????????????";
var up = username + ":" + password;
var authHeader = "Basic " + btoa(username + ":" + password);

WooClient.prototype.getProducts = function () {
    return $.ajax({
        url: "/myshop/wp-json/wc/v1/products",
        type: "get",
        dataType: "json",
        xhrFields: {
            withCredentials: true
        },
        beforeSend: function (xhr) {
            xhr.setRequestHeader("Authorization", authHeader);
            return true;
        }
    }).then(function (data) {
        return data;
    });
};

The same request performed with Advanced Rest Client returns "200 OK" and the desired result in the body.

Upvotes: 0

Views: 890

Answers (1)

Jonas Feragen
Jonas Feragen

Reputation: 11

I had the same issue. Also noticed that it worked in Edge, but not in Chrome. After I tried stripping the config down to the minimum, it suddenly started working for some reason. After digging some more, it seems like this happens whenever youre logged in to the same site.

$.ajax({
  url: "/wp-json/wc/v1/products",
  beforeSend: function(xhr) { 
    xhr.setRequestHeader("Authorization", "Basic " +btoa(username+':'+password)); 
    return true; 
  }
});

Of course, exposing your API keys to the browser is a very bad idea, if youre using this for something important :)

Upvotes: 1

Related Questions