HTTP Basic Authentication in AngularJS

By

Basic Authentication is an HTTP authentication framework in which user’s must provide a valid username and password to access secure endpoints. Many third-party APIs (for example, GitHub) support Basic Authentication as an authentication method.

I recently worked on an AngularJS application that required integration with GitHub. In order to make authorized requests to GitHub’s API, I set up an HTTP interceptor to handle Basic Authentication.

Setting up our Interceptor

The first thing we need to do is set up our interceptor. Let’s create a new file called basic.auth.interceptor.service.js and add the basic skeleton for our framework:

(function() {

    'use strict';

    angular
        .module('github-app')
        .factory('BasicAuthInterceptorService', BasicAuthInterceptorService);

    function BasicAuthInterceptorService() {

        var basicAuthInterceptorService = {
            request: request
        };

        return basicAuthInterceptorService;

        function request(config) {
            return config;
        }
    }

})();

So far our interceptor does absolutely nothing. We’ll get back to that shortly. For now, let’s register our new interceptor to our application. I usually have an app.module file which sets up my Angular application and loads all dependencies. Let’s open up that file and register our interceptor.

angular
    .module('github-app', [])

    .config(function($httpProvider) {
        $httpProvider.interceptors.push('BasicAuthInterceptorService');
    });

Nice! Now every time we make an HTTP request, the request function from inside of our interceptor will be triggered first.

Basic Authentication

Basic Authentication is actually super easy to set up. Before we start adding code to our interceptor, lets see what’s going on behind the scenes when we make a request using Basic Authentication.

Postman is a great tool for simulating HTTP requests. If you haven’t used it before, I highly recommend it.

Postman allows us to set up our Authorization Type when creating a request. Let’s select Basic Auth from the dropdown list. Now we’ll be prompted to enter our username and password. Let’s enter our GitHub credentials in here.

GitHub’s API lets us easily find all commits from a specified repo using the following endpoint:

GET /repos/:owner/:repo/commits

Let’s replace owner with the owner’s username, and repo with the name of our repository. Let’s paste this URL into Postman (making sure our HTTP method is set to GET) and click Send. Bam! You should see a JSON representation of all the commits from our repo. Nice!

Now click on the Headers tab to see what Postman did in the background for us. You’ll notice it added a header with the key Authorization and value Basic followed by a long sequence of characters. These characters are actually a Base64 encoded representation of our GitHub access token. This is what we’ll need to add to our interceptor to enable Basic Auth in our application.

Setting up Basic Authentication

Now that we know what we must do to enable Basic Auth from our application, let’s open up our interceptor and start writing some code.

The first thing we want to do is set up our interceptor to only intercept requests made to GitHub. We do not want our application to add Basic Auth for all requests. Let’s jump back into our request function from inside basic.auth.interceptor.service.js:

function request(config) {
    if (!config.url.includes('github.com')) {
        return config;
    } else {
        // TODO: Hook up Basic Auth
    }
}

Now all HTTP requests that aren’t routed to Github’s API will be returned with the default config.

The next step is implementing Basic Auth by adding a new key/value pair to all HTTP request headers to GitHub’s API. It’s important to note that Basic Authentication credentials are encoded with Base64 in transit. Therefore it’s not as simple as creating a header with the key Authorization and the value Basic <YOUR_ACCESS_TOKEN>. We actually need to encode our access token in Base64 first, and then add it to the header.

There are many libraries available that support Base64 encoding. I’ll be using angular-base64. If you’re using Bower then run bower install angular-base64 or just simply download the .zip file and include it as a separate script. Once installed, we can include the module in our app by editing our app.module.js file:

angular
    .module('github-app', [
        $base64
    ])

Okay, we’re good to go! Now we can inject $base64 as a dependency in our BasicAuthInterceptorService and use it to encode our access token. Then all we have to do is add a new header before sending our HTTP request.

function request(config) {
    if (!config.url.includes('github.com')) {
        return config;
    }

    var accessToken = $base64.encode(<YOUR_ACCESS_TOKEN>);
    config.headers['Authorization'] = 'Basic ' + accessToken;

    return config;
}

And that’s all there is to it. You’ll need to replace <YOUR_ACCESS_TOKEN> with the actual access token provided by GitHub. This can be found in your GitHub account settings. Once we have added our access token, we’ll be able to make requests to secure endpoints on GitHub’s API. Pretty cool!

Security

Please keep in mind that although our interceptor works, I still recommend making some changes before deploying to production. Our interceptor service is currently exposing our access token for the world to see. This is a huge security risk. We’ll need to add an extra layer of security to prevent user’s from being able to see our access token. For example, a combination of Amazon S3 and Amazon Cognito might just do the trick.