Categories
CoCart Core

Basic Authentication with CoCart

The core of CoCart needs to have all the basic requirements for any developer to have the base of the API ready to work out of the box for their development and authentication is one of them.

With CoCart v3, basic authentication is now built in and works like a charm.

Considering your web host allows authentication. If not, a little configuration to your .htaccess file will do the trick.

Simply add this to your .htaccess file and the authentication header will pass.

<IfModule mod_rewrite.c>
RewriteEngine on
RewriteCond %{HTTP:Authorization} ^(.*)
RewriteRule ^(.*) - [E=HTTP_AUTHORIZATION:%1]
</IfModule>

As for security, basic authentication is recommended to be used on secure sites that have SSL enabled, so if you or anyone attempts to use the API on the site without it being secured. Then it will simply fail.

Unless you are testing on a local or development environment, CoCart will not allow you to authenticate via the basic method.

In addition to being able to authenticate via basic method. Unlike the basic authentication plugin provided by WordPress (which is also outdated a little), CoCart identifies email addresses as a username.

curl -X POST https://example.com/wp-json/cocart/v1/add-item \
  -u addtocart@cocart.xyz:password \
  -H "Content-Type: application/json" \
  -d '{
    "product_id": "35",
    "quantity": 1
  }'

This is helpful should the customer forget the username they created or was assigned when registering as a customer and use their email address (along with their password) instead.

Oh and one more thing. Should it not be possible to authenticate the right way using the headers, you can authenticate the user via URL.

https://example.com/wp-json/cocart/v1/add-item?username=addtocart@cocart.xyz&password=password

Please keep your sites secure! ?

%d bloggers like this: