In my previous article, I explained how to implement Token Based Authentication in Web API. This article will demonstrate how to implement Token Based Authentication in AngularJS application.
Security is the main concern when you are creating a client application. In AngularJS, you have to take care when sending your credentials from the client side. You don’t want to send credentials with every request. When you use the Token Based Authentication, you do not need to send secure data every time to the server. You have to send your credentials once and the server will return a secure token. This token could be saved at client side and the next request will use this token to process a request. You can define expiry of the token as well.
So, let us move to the demonstration part. Create an empty solution in Visual Studio and set up all required as in the following image. We will cover every file’s task one by one with the following demonstration.

First, you have to create app.js at the root level, which contains the application module and its dependencies like routing module. Here, you need to create a constant named “appSetting” and define the base service URL that will be used to fetch data from the server [I am using localhost URL for this demonstration]. To implement UI routing, we are using “ui-router” as a dependency and respectively defining a different route.
Every time we send a request, we get a response from the server. Before processing any request, we have to modify the data or need to add some data like headers data with the request. When the response data returns, it could be anything; it might be some exceptions also. If anything happens wrong, then we have to handle everything, so for this, we have added an Interceptor named as “AuthInterceptor”.
APP.JS
- (function () {
- 'use strict';
- var app = angular.module("mukeshApp", ['ui.router']);
- app.constant("appSetting", {
- apiBaseUrl: "http://localhost:58238/"
- });
- app.config(['$stateProvider', '$urlRouterProvider', '$locationProvider', function ($stateProvider, $urlRouterProvider, $locationProvider) {
- $urlRouterProvider.otherwise('/home');
- $locationProvider.hashPrefix('');
- $stateProvider.state('default', {
- url: '/',
- templateUrl: '/app/components/home/index.html',
- controller: 'HomeCtrl'
- })
- .state('home', {
- url: '/home',
- templateUrl: '/app/components/home/index.html',
- controller: 'HomeCtrl'
- })
- .state('login', {
- url: '/account/login',
- templateUrl: '/app/components/login/index.html',
- controller: 'LoginCtrl'
- });
- }
- ]);
- app.config(['$httpProvider', function ($httpProvider) {
- $httpProvider.interceptors.push('AuthInterceptor');
- }]);
- app.config(['$qProvider', function ($qProvider) {
- $qProvider.errorOnUnhandledRejections(false);
- }]);
- })();
AUTHINTERCEPTOR.JS
Here, AuthInterceptor will handle every request and response as well as request error and response error. If any error returns, the application moves to the login page, otherwise it will redirect to home page.
If the user is already logged in and a validated token has already been added in session, then for the next request, we will not send credentials to the server. We will pick the token from session item and add token with the request.
- (function (app) {
- app.factory('AuthInterceptor', ['$log', '$state', '$q', function ($log, $state, $q) {
- $log.debug('$log is here to show you that this is a regular factory with injection');
- var authInterceptor = {
- request: function (config) {
- var accessToken = sessionStorage.getItem('accessToken');
- if (accessToken == null || accessToken == "undefined") {
- $state.go("login");
- }
- else {
- config.headers["Authorization"] = "bearer " + accessToken;
- }
- return config;
- },
- requestError: function (config) {
- $state.go("login");
- return config;
- },
- response: function (res) {
- return res;
- },
- responseError: function (res) {
- if (res.status == "401") {
- $state.go("login");
- }
- if (res.status == "400") {
- $state.go("login");
- }
- if (res.status == "403") {
- $state.go("login");
- }
- if (res.status == "404") {
- $state.go("login");
- }
- $q.reject(res)
- return res;
- }
- };
- return authInterceptor;
- }]);
- })(angular.module("mukeshApp"));
EMPLOYEESERVICE.JS
In the previous part, we have created a Web API Employee Controller which has GetEmployees(). It returns employees data. So, to get employee data from the database, we are creating a service named “EmployeeService”. This will make an API call which we have already made in my previous part.
- (function (app) {
- 'use strict';
- app.factory("EmployeeService", ["$http", "appSetting", "$q", EmployeeService]);
- function EmployeeService($http, appSetting, $q) {
- this.GetAll = function () {
- var deffered = $q.defer();
- var query = $http.get(appSetting.apiBaseUrl + "api/employee/GetEmployees");
- return query.then(function (response) {
- deffered.resolve(response.data);
- return deffered.promise;
- }, function (response) {
- deffered.reject(response);
- return deffered.promise;
- });
- };
- return {
- GetAll: this.GetAll
- }
- };
- })(angular.module("mukeshApp"));
LOGINSERVICE.JS
This service will be used to log in with Server using provided credentials. Please don’t forget to pass grant_type = “password”.
- (function (app) {
- 'use strict';
- app.factory("LoginService", ["$http", "appSetting", LoginService]);
- function LoginService($http, appSetting) {
- this.login = function (userData) {
- var response = $http({
- url: appSetting.apiBaseUrl + 'token',
- method: 'POST',
- data: $.param({
- grant_type: userData.grant_type,
- username: userData.username,
- password: userData.password
- }),
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
- });
- return response;
- };
- return {
- login: this.login
- }
- };
- })(angular.module("mukeshApp"));
HOMECTRL.JS
To fetch and display the data on home page, we are creating HomeCtrl controller. Here, getAllEmployees function will get the all employee data and bind with $scope.employees.



Rafael AlvarezPosted Oct 1, 2018, 6:04 PM
Excellent, very good. Thanks
Ham VuiPosted Sep 17, 2018, 11:05 PM
Please share your code. Thanks
Tridip BhattacharjeePosted Apr 11, 2018, 3:53 AM
What is $state.go("login"); and what it will do ?
mido assafPosted Nov 18, 2017, 7:09 AM
Shall you upload the code ?? ... i follow all the steps and it didn't work
pramod gorityalaPosted Oct 28, 2017, 8:23 AM
Can u give me application ... i mean code