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.
Token Based Authentication in Web API
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.
(function (app) {
'use strict';
app.controller('HomeCtrl', ['$scope', 'EmployeeService', HomeCtrl]);
function HomeCtrl($scope, EmployeeService) {
$scope.getAllEmployees = function () {
EmployeeService.GetAll().then(function (result) {
$scope.employees = result;
}, function (error) {
console.log("Bad Request Process");
});
};
$scope.init = function () {
$scope.getAllEmployees();
};
$scope.init();
};
})(angular.module("mukeshApp"));
Once you will get data, you have to show it to the user interface. So, as in the following, you have to use “ng-repeat” to use the rendered data as table format.
<div class="row">
<div class="col-lg-2">
</div>
<div class="col-lg-8">
<h2>Token Based Authentication in AngularJS </h2>
<br />
<div class="panel panel-default">
<div class="panel-heading">
Employee List
</div>
<div>
<table width="100%" class="table table-striped table-bordered table-hover" id="dataTables-example">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="emp in employees">
<td>{{emp.id}}</td>
<td>{{emp.name}}</td>
<td>{{emp.address}}</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
LOGINCTRL.JS
It will take credentials from user screen and create user object, which also contains grant_type as “password”. Once you log in successfully, you can set token in sessionStorage for further use and redirect to home page.
(function (app) {
'use strict';
app.controller('LoginCtrl', ['$scope', '$state', 'LoginService', LoginCtrl]);
function LoginCtrl($scope, $state, LoginService) {
$scope.user = [];
$scope.userName = "";
$scope.password = "";
$scope.userDisplayName = "";
$scope.isAuthenticated = true;
$scope.logout = function () {
};
$scope.loggedIn = function () {
$scope.user = {
grant_type: 'password',
username: $scope.userName,
password: $scope.password
};
if ($scope.userName == "" || $scope.password == "") {
$scope.isAuthenticated = false;
$state.go("login");
}
else {
var promise = LoginService.login($scope.user);
promise.then(function (resp) {
if (resp.data != null) {
if (resp.data.error == "invalid_grant") {
$scope.isAuthenticated = false;
$state.go('login');
}
else {
$scope.isAuthenticated = true;
sessionStorage.setItem('userName', $scope.userName)
sessionStorage.setItem('accessToken', resp.data.access_token)
sessionStorage.setItem('userName', $scope.userName)
$state.go('home');
}
} else {
$scope.isAuthenticated = false;
$state.go("login");
}
}, function () {
$scope.isAuthenticated = false;
$state.go("login");
}, function () {
console.log("C");
$scope.isAuthenticated = false;
$state.go("login");
});
}
};
};
})(angular.module("mukeshApp"));
Following is the template for login page.
<div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
<div class="panel panel-success">
<div class="alert alert-danger" ng-if="!isAuthenticated">
<strong>Oh Sorry!</strong> Incorrect user name or password, try again.
</div>
<div class="panel-heading">
<div class="panel-title center">Sign In</div>
<div class="panel-body">
<form class="form-horizontal" role="form">
<div class="input-group input-username">
<span class="input-group-addon"></span>
<input type="text" class="form-control" name="username" placeholder="username" ng-model="userName" autofocus>
</div>
<div class="input-group input-password">
<span class="input-group-addon"></span>
<input type="password" class="form-control" name="password" placeholder="password" ng-model="password">
</div>
<div class="input-group checkbox-remember">
<div class="checkbox">
<label><input id="login-remember" type="checkbox" name="remember" value="1"> Remember me</label>
</div>
</div>
<div class="form-group login-button">
<div class="col-sm-12 controls">
<input type="submit" class="btn btn-success" value="Login" ng-click="loggedIn()" />
</div>
</div>
</form>
</div>
</div>
</div>
Here is the final index.html that contains all the references.
<!DOCTYPE html>
<html lang="en">
<head>
<base href="/" />
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<!-- Meta, title, CSS, favicons, etc. -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Token Based Authentication Example - Mukesh Kumar</title>
<link href="App/Assests/Css/bootstrap.min.css" rel="stylesheet" />
<link href="App/Assests/Css/sb-admin.css" rel="stylesheet" />
</head>
<body class="nav-md" ng-app="mukeshApp">
<div ui-view></div>
<script src="App/Assests/Js/jquery.min.js"></script>
<script src="App/Assests/Js/bootstrap.min.js"></script>
<script src="App/Assests/Js/angular.min.js"></script>
<script src="http://angular-ui.github.io/bootstrap/ui-bootstrap-tpls-0.10.0.js"></script>
<script src="App/Assests/Js/angular-ui-router.min.js"></script>
<script src="App/app.js"></script>
<script src="app/Components/Home/HomeCtrl.js"></script>
<script src="app/Common/Services/EmployeeService.js"></script>
<script src="App/Components/Login/LoginCtrl.js"></script>
<script src="App/Common/Services/LoginService.js"></script>
<script src="App/Common/Services/Factory/AuthInterceptor.js"></script>
</body>
</html>
Now, it is time to run the application. Once you run the application, it will automatically redirect to the login page because token is not available right now. On the login page, you just need to provide the correct credentials and it will redirect to the home page.
Once you provide username and password and click the login button, it will redirect to the home page as following.
Conclusion
Today, we have seen how to implement Token Based Authentication in AngularJS application.
I hope this post helps you. Please put your feedback using comments, which will help me improve for the next post. If you have any doubts, please ask in the Comments section.
Posted Comments :
kumar Posted : 6 Years Ago
Hi can you mail me source code for web-api-token-based-authentication-with-angular-js this is my email id : kumaraspcode2009@gmail.com
Ripon Kumar Posted : 6 Years Ago
Dear Sir, would u plz provide me AngularJs Source Code. Then I would be very helpful.
rendy Posted : 5 Years Ago
Hi can you mail me source code for web-api-token-based-authentication-with-angular-js this is my email id : rendyprox@gmail.com
Hoang Posted : 4 Years Ago
Can you email me this project? Thx
tirupathirao Posted : 7 Years Ago
Thanks, I learned lot from this