Basic Authentication with the WP-API (v2) and AngularJS

Working on the WP-App Project, we need to use authentication to do certain things in the app. Deleting/approving comments, or listing users for example.

Basic Authentication is handy for testing code, but it should only be used in development, since you send the user/pass with every request. For production, you’ll want to use OAuth from an external client like a mobile app. I haven’t dug into OAuth yet, but it’s documented a little bit here.

We are using the Ionic Framework for the WP-App Project, which is based on AngularJS. Basic authentication requires sending the username and password, base64 encoded, in the request header. Here’s what that looks like.

Requirements

Basic authentication requires the Basic Auth plugin to be installed, along with the WP-API v2.

Services

First we need a Base64 service, because we aren’t using a library that does that automatically for us. This code goes in services.js, or whatever file you have your factories in.

Next we need our data loader, you can put this right below the Base64 service, in the same file.

.factory('DataLoader', function( $http ) {

  return {
    get: function(url) {
      return $http.jsonp( url );
    },
    getAuth: function(base64, url) {
      
      $http.defaults.headers.common['Authorization'] = 'Basic ' + base64;

      var req = { method: 'GET', url: url }

      return $http( req );
    },
}
});

The auth part is setting the authorization headers to use Basic auth, and send along our encoded username and password.

Controller

Now in our controller, we can use the services above. This would ideally go in a different file, such as controllers.js.

angular.module('myApp.controllers', [])

// Make sure to inject our services for DataLoader and Base64
.controller('myCtrl', function($scope, DataLoader, Base64 ) {

  var username = 'user';
  var password = '123456';

  // use our Base64 service to encode the user/pass
  var base64 = Base64.encode( username + ':' + password );
  // Some endpoint that needs auth
  var dataURL = 'https://mysite.com/wp-json/wp/v2/users';

    DataLoader.getAuth( base64, dataURL ).then(function(response) {

        $scope.data = response.data;

      }, function(response) {

        console.log('Error');
        $ionicLoading.hide();

    });

});

We can use this same method to send other authenticated requests, such as PUT and DELETE. To do that, you would just change the req variable in the getAuth function like this:

var req = {
  method: 'DELETE',
  url: url
}

Remember that basic auth is not for production, and using https is always a good idea.

Using basic authentication, you should be able to experiment with getting authenticated data such as listing users, and deleting posts or other items. Using PUT or POST requires sending additional data, I’ll tackle that in another post.

Cheers!


Get more content like this

Get valuable insight on business and money in your inbox once per week.

Posted by Scott

  1. Alain Boudard (@aboudard) March 11, 2016 at 9:19 am

    Hello !
    Thank you for the clear explanation about the requests.
    I’m stuck with this basic auth and totally missed the base64 part in the documentation !
    I’ll test that right now 🙂

    Reply

  2. Hi, this http header common break my others http request on my angular app.
    By the way, a simple way to convert to base64:
    var base64 = btoa(username + ‘:’ + password);
    http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_win_btoa

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Being a business owner is hard. I'm trying to get better in business and life, enter your email if you want to join me.
Holler Box