Friday

How to pass authentication token to AngularJS component


AngularJS is so popular nowadays. Most likely you are already using or want to. An interesting question is when you integrate Angular components into existing secured web app, how do you secure you Angular components. Note that these UI components may be sending HTTP request to a different server than existing ones. One common approach is to pass security token from existing web page to the new Angular components, which is then passed over onto server side for security checks. This article uses a demo app to explain the solution. Complete working code samples can be found in my GitHub

Download all files into the same web folder of your test server. I like to use browser-sync. Follow the link to learn how to use browser-sync. It helps you to understand better if you run the demo app while reading.

Index.html: This is the starting point of the sample web app. Assume you have an existing credit card  web app on which there is already a login button. And you want to add a new set of features like credit card notification features, using secured AngularJS components. You want your customers to login and manage notification preferences.


In the login() method of index.html, you use 
sessionStorage.setItem('token', 'ABCDE');
to store the authentication token obtained from server side, which is displayed on page for purpose of demo.

After login, customer clicks "Continue to Notification Center after login", which opens up Notification.html. It contains Angular app called "app".


The Angular app is defined in app.js. prefController initialization also defines available notification types, which is for demo purpose. Note how it gets token from session storage:
$scope.token = $window.sessionStorage.getItem('token');


It also includes 'pref' directive, defined by "granularpref.html":


where customer's notification preferences are mapped to model pref.optIn.

Upon submit, the preferences are saved by function 'savePref()', which is only for demo purpose. The key take away is that you use $window to pass value into Angular controller, and read token stored in sessionStorage and store in $scope, as displayed on the page (see {{token}} in granularpref.html. In real world, you would send this token to backend for authentication. 

No comments: