Thursday, January 19, 2017

AngularJS with Web Api in Asp.net MVC using Token based Authentication

Here in this Post I will show how to use Token based Authentication using AngularJS and Web Api 2 in Asp.Net MVC. Previous posts I had shown how to
DataTables in MVC:
AngularJS:



















Before going through this POST please go through the below post

Create a New Project in VS 2015 using Asp.Net MVC with (Change Authentication) Authentication : Individual User Accounts.

Add Index.html in the project and Set As Start Page.

Now create a New folder as Modules
In the modules folder create another 3 folders as Controllers, Services, Views

Create App.js file in Modules folder.
In the Views folder ADD the following HTML pages Register, Login, Home, Customers, Books.
In the Services folder ADD RegisterServices, LoginServices, HomeServices, Customer & Books too.
In the Same way Controllers folder also. The entire Folder looks as shown below.
As said above use the Code First Migrations in MVC 5 procedure, here we are continuing the same post.
Add the packages Jquery, bootstrap, angularjs, toastr.js and include them in the Index.html page with related css. Add the bootstrap nav bar also. The entire page looks as shown below.
  

<!DOCTYPE html>
<html ng-app="AngularApp">
<head>
    <title></title>
    <link href="Content/DataTables/css/dataTables.bootstrap.css" rel="stylesheet" />
    <link href="Content/toastr.css" rel="stylesheet" />
    <link href="Content/bootstrap.css" rel="stylesheet" />
    <script src="AngularDT/jquery-2.2.4.min.js"></script>
    <script src="Scripts/bootstrap.js"></script>
    <script src="Scripts/angular.js"></script>
    <script src="Scripts/angular-route.js"></script>
    <script src="Scripts/angular-ui/ui-bootstrap-tpls.js"></script>
    <script src="Scripts/angular-ui/ui-utils.js"></script>
    <script src="Scripts/DataTables/jquery.dataTables.js"></script>
    <script src="Scripts/DataTables/dataTables.bootstrap.js"></script>

    <script src="Modules/app.js"></script>
    <script src="Modules/Services/LoginService.js"></script>
    <script src="Modules/Services/RegisterService.js"></script>
    <script src="Modules/Controllers/LoginController.js"></script>
    <script src="Modules/Controllers/RegisterController.js"></script>
    <script src="Modules/Controllers/HomeController.js"></script>
    <script src="Modules/Controllers/CustomersController.js"></script>
    <script src="Modules/Controllers/BooksController.js"></script>
    <script src="Modules/Services/BooksService.js"></script>
    <script src="Modules/Controllers/ModalPopUpController.js"></script>
    <script src="Modules/Services/HomeService.js"></script>
    <script src="Modules/Controllers/EmployeeController.js"></script>
    <script src="Modules/Services/EmployeeService.js"></script>
    <!--<script src="Modules/Controllers/NavBarController.js"></script>
    <script src="Modules/Services/navBarService.js"></script>-->
    <script src="Scripts/toastr.js"></script>

</head>
<body class="container">
    <!--ng-controller="NavbarController" ng-hide="show"-->
    <!--<nav class="navbar navbar-inverse navbar-fixed-top">-->

    <nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="#/home">WebSiteName</a>
            </div>
            <ul class="nav navbar-nav">
                <li class="active"><a href="#/home">Home</a></li>
                <li class="dropdown">
                    <a class="dropdown-toggle" data-toggle="dropdown">Page 1 <span class="caret"></span></a>
                    <ul class="dropdown-menu">
                        <li><a href="#/books">Books</a></li>
                        <li><a href="#/customers">Customers</a></li>
                        <li><a href="#/employees">Employees</a></li>
                    </ul>
                </li>
                <li><a href="#/books">Books</a></li>
                <li><a href="#/customers">Customers</a></li>
                <li><a href="#/employees">Employees</a></li>
            </ul>
            <ul class="nav navbar-nav navbar-right">
                <!--<li><a href="#"><span class="glyphicon glyphicon-user"></span> Sign Up</a></li>-->
                
                <li><a href="#">Welcome {{userName}}</a></li>                
                <li><a href="#login"><span class="glyphicon glyphicon-log-out"></span> Logout</a></li>
            </ul>
        </div>
    </nav>
    <br />
    <br />
    <br />
    <br />
    <div  ng-view></div>

</body>
</html>
In the App.js file add the following angularjs scrippt with routing.
  

var app = angular.module("AngularApp", ["ngRoute", 'ui.bootstrap', 'ui.utils']);

app.config(function ($routeProvider, $locationProvider) {

    $routeProvider
        .when("/register", {
            templateUrl: "/Modules/Views/Register.html",
            controller: "registerUserController"
        })
        .when("/login", {
            templateUrl: "/Modules/Views/Login.html",
            controller: "loginController"
        })
        .when("/home", {
            templateUrl: "/Modules/Views/Home.html",
            controller: "homeController"
        })
        .when("/books", {
            templateUrl: "/Modules/Views/Books.html",
            controller: "booksController"
        })
        .when("/customers", {
            templateUrl: "/Modules/Views/Customers.html",
            controller: "customersController"
        })
        .when("/employees",{
            templateUrl: "/Modules/Views/Employees.html",
            controller:"employeeController"
        })
        .otherwise({
            redirectTo: "/login"
        });
    $locationProvider.html5Mode(false).hashPrefix('');
});

Open registerservice.js file and ADD the following script.
  

app.factory("registerUserService",
    ["$http",
    function ($http) {

        var registerUser = function (userRegister) {
            var resp = $http({
                url: '/api/Account/Register',
                method: "POST",
                data: userRegister
            });
            return resp;
        };

        return {
            registerUser: registerUser
        };
    }]);

Open registercontroller.js file and ADD the following script in it.
  


app.controller("registerUserController",
    ["$scope", "registerUserService", "$uibModal", "$location",
        function ($scope, registerUserService, $uibModal, $location) {

            $scope.responseData = "";
            $scope.userName = "";

            $scope.userRegistrationName = "";
            $scope.userRegistrationEmail = "";
            $scope.userRegistrationPassword = "";
            $scope.userRegistrationConfirmPassword = "";

            $scope.RegisterUser = function () {
                $scope.responseData = "";

                $scope.userRegistrationInfo = {
                    userName: $scope.userRegistrationName,
                    Email: $scope.userRegistrationEmail,
                    Password: $scope.userRegistrationPassword,
                    ConfirmPassword: $scope.userRegistrationConfirmPassword
                };

                var promiseUserRegister = registerUserService.registerUser($scope.userRegistrationInfo);
                promiseUserRegister.then(function (resp) {
                    $scope.responseData = "Registered Successfully.";
                    $scope.userRegistrationEmail = "";
                    $scope.userRegistrationPassword = "";
                    $scope.userRegistrationConfirmPassword = "";
                    $scope.userRegistrationName = "";

                    // $uibModal.open({
                    //    keyboard: false,// keyboard Esc
                    //    templateUrl: "/Modules/Views/ModalPopupMsg.html"
                    //});

                    toastr.success($scope.responseData);
                    $location.path("/login");
                }, function (err) {
                    var errors = [];
                    var errorsString = "";
                    var modelState = err.data.ModelState;
                    for (var key in modelState) {
                        if (modelState.hasOwnProperty(key)) {
                            for (var i = 0; i < modelState[key].length; i++) {
                                errorsString = (errorsString == "" ? "" : errorsString + "<br/>") + modelState[key][i];
                                errors.push(modelState[key][i]);
                            }
                        }
                    }

                    //toastr.success("awesome", "totally").css("width","500px")
                    toastr.error("<ul><li>" + errors.join(" </li><li> ") + "</ul>");//Chnged Toastr Width in CSS to 500px
                });
            };

            $scope.go = function (path) {
                $location.path(path);
            };

        }]);

Open register.html page and add the following html tags.
  

<form role="form" class="form-horizontal">
    <fieldset>
        <legend>Register User</legend>

        <div class="form-group">
            <label for="Name" class="col-sm-3 control-label">Name</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" id="Name" name="Name" ng-model="userRegistrationName" />
            </div>
        </div>
        <div class="form-group">
            <label for="Email" class="col-sm-3 control-label">Email</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="Email" id="Email" ng-model="userRegistrationEmail" />
            </div>
        </div>
        <div class="form-group">
            <label for="password" class="col-sm-3 control-label">Password</label>
            <div class="col-sm-9">
                <input type="password" name="password" id="password" class="form-control" ng-model="userRegistrationPassword" />
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label" for="ConfirmPassword">Confirm Password</label>
            <div class="col-sm-9">
                <input type="password" class="form-control" id="ConfirmPassword" name="ConfirmPassword" ng-model="userRegistrationConfirmPassword" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <div class="col-sm-9">
                <input type="submit" ng-click="RegisterUser()" class="btn btn-primary" value="Register" />
                <input type="button" class="btn btn-success" ng-click="go('/login')" value="Login"/>
            </div>
        </div>
    </fieldset>
</form>

Now open loginservice.js file and add the following code.
  

app.factory("loginUserService", ["$http", function ($http) {

    var Login = function (userlogin) {
        var resp = $http({
            url: "/TOKEN",
            method: "POST",
            data: $.param({ grant_type: "password", username: userlogin.username, password: userlogin.password }),
            headers: { 'Content-Type': 'application/x-www-form-urlencoder' }
        });
        return resp;
    };
    return {
        Login: Login
    };
}]);

Open logincontroller.js file and add the following code in it.
  

app.controller("loginController",
    ["$scope", "$uibModal", "$location", "$rootScope", "loginUserService",
        function ($scope, $uibModal, $location, $rootScope, loginUserService) {
            $scope.IsAuthenticated = false;

            $scope.go = function (path) {
                $location.path(path);
            };
            
            //#region Login
            $scope.responseData = "";
            $scope.userName = "";

            $scope.userLoginEmail = "";
            $scope.userLoginPassword = "";

            $scope.accesToken = "";
            $scope.refreshToken = "";

            $scope.Login = function () {
                var loginInfo = {
                    username: $scope.userLoginEmail,
                    password: $scope.userLoginPassword
                };

                var promiseLogin = loginUserService.Login(loginInfo);
                promiseLogin.then(function (resp) {
                    $scope.userName = resp.data.userName;

                    sessionStorage.setItem("userName", resp.data.userName);
                    sessionStorage.setItem("accessToken", resp.data.access_token);                    
                    $scope.IsAuthenticated = true;
                    $location.path("/home");
                }, function (err) {
                    var errors = [];
                    var errorsString = "";
                    var modelState = err.data;
                    console.log(modelState);                    
                    errors.push(modelState.error_description);
                    //toastr.success("awesome", "totally").css("width","500px")
                    toastr.error("<ul><li>" + errors.join(" </li> ") + "</ul>");//Chnged Toastr Width in CSS to 500px
                });
            };
            //#endregion
            
        }]);

Open login.html page and add the following.
  

<form role="form" class="form-horizontal">    
    <fieldset>
        <legend>Login</legend>
        <div class="form-group">
            <label class="col-sm-3 control-label" for="Email">Email or UserName</label>
            <div class="col-sm-9">
                <input type="text" class="form-control" name="Email" id="Email" ng-model="userLoginEmail"/>
            </div>
        </div>
        <div class="form-group">
            <label class="col-sm-3 control-label" for="password">Password</label>
            <div class="col-sm-9">
                <input type="password" name="password" id="password" class="form-control" ng-model="userLoginPassword"/>
            </div>
        </div>
        <div class="form-group">
            <div class="col-sm-3"></div>
            <div class="col-sm-9">
                <input type="button" style="width:150px;" class="btn btn-primary form-control" value="Login" ng-click="Login()" />
                <input type="button" value="Open PopUp" class="btn btn-default" ng-click="OpenPopUp()"/>
                <input type="button" class="btn btn-success pull-right" value="Register" ng-click="go('/register')"/>
            </div>
        </div>
    </fieldset>
</form>

  





Will Update ASAP...


No comments:

Post a Comment