AngularJS User Registration in MVC with Password Encryption

Introduction
  •  When we starts with registering users on any application or website.One thing is to care about that is security of data.
  • Passwords is the most sensitive information to travel throughout the internet ,so that should be securely transfered to the internet.
  • This article tells how to encrypt the password and registers the user with other information.
  • ADO.NET model is used as data access technique here,MVC is used with angularjs.    
 
   
 
Create database and tables
  • Firstly Create database named TestData.
  • After creating the database create a table with the name Logins.


 
 
  • Set the Id column as primary key and auto increment id in every table.
  • That's it with the database.
 
Download JS and CSS files from given links

Are you new with AngularJS ?

  • Visit this link for more information on AngularJS.
 
Start writing  code
 
  • Open the VS2012 ,Create New ASP.Net MVC4 Web Application and give the Name AuthenticationAngularMvcApp.
  • Go to Models Folder in the solution explorer of visual studio.
  • Right click the Models folder and find ADD >>> ADO.NET Entity Data Model. Select ADO.NET Entity Data Model.
  • Provide the name DbModel. After that pop up will appear .

     

  •  Select generate from database, click Next.

     

  • In the given box type entity name as SahilEntities and After that click New connection.

     

 
  •  Select Sql server authentication and fill the credentials like server name ,user name ,password,and then select your database from the database list.

       

 
  • Check the checkboxes of tables and click on finish.


   Register CSS and JS in Bundle.Config
 
  • Go to the App_Start folder find BundleConfig.cs write the below given code.

  

  1. using System.Web;  
  2. using System.Web.Optimization;  
  3.   
  4. namespace AuthenticationAngularMvc  
  5. {  
  6.     public class BundleConfig  
  7.     {          
  8.         public static void RegisterBundles(BundleCollection bundles)  
  9.         {  
  10.             RegisterScript(bundles);  
  11.             RegisterStyle(bundles);  
  12.         }  
  13.   
  14.         public static void RegisterScript(BundleCollection bundles)  
  15.         {  
  16.             bundles.Add(new ScriptBundle("~/js")  
  17.                 .Include("~/Scripts/jquery-{version}.js")  
  18.                 .Include("~/Scripts/jquery-ui-{version}.js")  
  19.                 .Include("~/Scripts/bootstrap.js"));  
  20.         }  
  21.   
  22.         public static void RegisterStyle(BundleCollection bundles)  
  23.         {  
  24.             bundles.Add(new StyleBundle("~/css")  
  25.                 .Include("~/Content/bootstrap.css")  
  26.                 .Include("~/Content/site.css"));  
  27.         }  
  28.     }  

 
Utility class to encrypt password
 
  •  Right click on the Refrence folder ,select Manage NuGet Packages.
  •  Search for Bcrypt,install by click on install button.
  •  Bcrypt is a cross platform file encryption utility.it calculates the hash algorithm for the plain text.
  •  It compares the hash at the time of login of user to give access.
  •  The biggest advantage of this algorithm is ,we cannot decrypt the password to plain text only hash is compared of 2 passwords.
  •  Add a folder named Utilities in the solution explorer.
  •  Create a class named Utility.Import namespace using BCrypt.Net; to access methods under Bcrypt namespace.     

     

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using BCrypt.Net;  
  7.   
  8. namespace AuthenticationAngularMVC.Utilities  
  9. {  
  10.     public static class Utility  
  11.     {  
  12.         public static string Encryptpassword(string password)  
  13.         {  
  14.             string hashedPassword = BCrypt.Net.BCrypt.HashPassword(password, BCrypt.Net.BCrypt.GenerateSalt(12));  
  15.             return hashedPassword;  
  16.         }  
  17.   
  18.         public static bool CheckPassword(string enteredPassword, string hashedPassword)  
  19.         {  
  20.             bool pwdHash = BCrypt.Net.BCrypt.Verify(enteredPassword, hashedPassword);  
  21.             return pwdHash;  
  22.         }  
  23.     }  

  • Here first method is used to encrypt password and second method is used to compare the password at the time of login.
  • In first method plain text password is passed to the method.
  • In second method plain text password and hashed password from database is passed for comparison.

 Start with Controller code

  • Go to the controller folder and create RegisterController in the folder.
  • Replace the Index ActionResult with Register.
  • Create CheckUser method with username as parameter to check the existence of user.
  • Create method for AddUser with Login class as parameter.
  • Here first we check if the data is present in the usr instance or not.
  • Then check if user is already present or not by CheckUser method.
  • Then create object of Logins class to store the data in fields.
  • Encrypt the password by using utility class and passing entered password in the utility class.
  • Utitliy class is a static class and it can be directly accessed without creating the object.

     

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using  AuthenticationAngularMvc.Models;  
  7.   
  8. namespace  AuthenticationAngularMvc.Controllers  
  9. {  
  10.     public class RegisterController : Controller  
  11.     {  
  12.         public ActionResult Register()  
  13.         {  
  14.           return View();  
  15.         }  
  16.           
  17.         //To check that user entered is already present or not.  
  18.         public bool CheckUser(string user)  
  19.         {  
  20.             bool Exists = false;  
  21.             using (SahilEntities context = new SahilEntities())  
  22.             {  
  23.                 var uName = context.Logins1.Where(x => x.UserName == user).ToList();  
  24.                 if (uName.Count != 0)  
  25.                 {  
  26.                     Exists = true;  
  27.                 }  
  28.             }  
  29.             return Exists;  
  30.         }  
  31.           
  32.         //For saving the user details in database table.          
  33.         public string AddUser(Login1 usr)  
  34.         {  
  35.             if (usr != null)  
  36.             {  
  37.                 if (CheckUser(usr.UserName) == false)  
  38.                 {  
  39.                     using (SahilEntities context = new SahilEntities())  
  40.                     {  
  41.                         Login1 createUser = new Login1();  
  42.                         createUser.UserName = usr.UserName;  
  43.                         createUser.Fname = usr.Fname;  
  44.                         createUser.Lname = usr.Lname;  
  45.                         createUser.Email = usr.Email;  
  46.                         createUser.DateTimeCreated = DateTime.Now;  
  47.                         createUser.Password = Utility.Encryptpassword(usr.Password);  
  48.                         context.Logins1.Add(createUser);  
  49.                         context.SaveChanges();  
  50.                     }  
  51.                     return "User created !";  
  52.                 }  
  53.                 else  
  54.                 {  
  55.                     return "User already present !";  
  56.                 }  
  57.             }  
  58.             else  
  59.             {  
  60.                 return "Invalid Data !";  
  61.             }  
  62.         }  
  63.     }  

Change path of default controller
 
  • Find RouteConfig.cs in App_Start folder and change the default Controller and Action.

     

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Web.Routing;  
  7.   
  8. namespace AuthenticationAngularMvc  
  9. {  
  10.     public class RouteConfig  
  11.     {  
  12.         public static void RegisterRoutes(RouteCollection routes)  
  13.         {  
  14.             routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  15.   
  16.             routes.MapRoute(  
  17.                 name: "Default",  
  18.                 url: "{controller}/{action}/{id}",  
  19.                 defaults: new { controller = "Register", action = "Register", id = UrlParameter.Optional }  
  20.             );  
  21.         }  
  22.     }  

Start with AngularJS code
 
  • Add Module.js,Controller.js,Service.js in content folder.
  • In Module.js start writing code.     
  1. var app = angular.module("myApp", []); 
  • app.Controller registers the angular controller with name myCntrl.
  • $scope is used to refers the application.Data passed in the $scope is accessible in view.
  • myService used to access the methods in the Service.js file.
  • In SaveUser function, Object User is used to store entered inputs by user.
  • Then response is used to store the response returned by AddUser method in the service.
  • At last message should be displayed on the screen according to the data returned from the service.

     

  1. app.controller("myCntrl"function ($scope, myService) {          
  2.           
  3.     $scope.SaveUser = function () {  
  4.         $("#divLoading").show();  
  5.         var User = {  
  6.             FName: $scope.fName,  
  7.             LName: $scope.lName,  
  8.             Email: $scope.uEmail,  
  9.             Password: $scope.uPwd,  
  10.             UserName: $scope.uName  
  11.     };  
  12.   
  13.     var response = myService.AddUser(User);  
  14.         response.then(function (data) {  
  15.         if (data.data == "1") {  
  16.             $("#divLoading").hide();  
  17.             clearFields();  
  18.             alert("User Created !");  
  19.             window.location.href = "/Register/Login";  
  20.         }  
  21.         else if (data.data == "-1") {  
  22.             $("#divLoading").hide();  
  23.             alert("user alraedy present !");  
  24.         }  
  25.         else {  
  26.             $("#divLoading").hide();  
  27.             clearFields();  
  28.             alert("Invalid data entered !");  
  29.         }  
  30.         });  
  31.     }  
  32.   
  33.     function clearFields() {  
  34.         $scope.fName = "";  
  35.         $scope.lName = "";  
  36.         $scope.Email = "";  
  37.         $scope.Password = "";  
  38.         $scope.UserName = "";  
  39.     }  
  40.           
  41. }); 
  • In Service.js app.Service is used to register the service with the application.
  • $http is used to call the server methods by providing url ,method,and data.
  • Returned response is then passed from where the function is called.

     

  1. app.Service("myService"function ($http) {  
  2.   
  3.     this.AddUser = function (User) {  
  4.         var response = $http({  
  5.             method: "post",  
  6.             url: "/Register/AddUser",  
  7.             data: JSON.stringify(User),  
  8.             dataType: "json"  
  9.         });  
  10.         return response;  
  11.     }  
  12. }); 
Add view for Registration
 
  • Go to the RegisterController ,right click on the Register Action, select AddView option.

     

  • Start writing code in RegisterView.

     

  1. @{  
  2.     ViewBag.Title = "Register";  
  3. }  
  4. <html ng-app="myApp">  
  5. <head>  
  6.     <title>Register</title>  
  7.     <script src="~/Content/Module.js"></script>  
  8.     <script src="~/Content/Service.js"></script>  
  9.     <script src="~/Content/Controller.js"></script>  
  10. </head>  
  11. <body>  
  12.   
  13.     <div class="container" ng-controller="myCntrl">  
  14.         <br />  
  15.   
  16.         <div class="row">  
  17.             <img src="~/Content/Images/user.png" /><h4>Register User</h4>  
  18.             <hr />  
  19.   
  20.             <br />  
  21.             <div class="col-md-6">  
  22.                 <form name="userForm" novalidate>  
  23.                     <div class="form-horizontal">  
  24.                         <div class="form-group">  
  25.                             <div class="row">  
  26.                                 <div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">  
  27.                                     First Name :   
  28.                                 </div>  
  29.                                 <div class="col-md-6">  
  30.                                     <input type="text" class="form-control" placeholder="First Name" name="fName" ng-model="fName" required autofocus />  
  31.                                 </div>  
  32.                             </div>  
  33.                         </div>  
  34.                         <div class="form-group">  
  35.                             <div class="row">  
  36.                                 <div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">  
  37.                                     Last Name :  
  38.                                 </div>  
  39.                                 <div class="col-md-6">  
  40.                                     <input type="text" class="form-control" placeholder="Last Name" name="lName" ng-model="lName" required autofocus />  
  41.                                 </div>  
  42.                             </div>  
  43.                         </div>  
  44.                         <div class="form-group">  
  45.                             <div class="row">  
  46.                                 <div class="col-md-3" style="margin-left: 15px; color: #5bc0de">  
  47.                                     Email :  
  48.                                 </div>  
  49.                                 <div class="col-md-6">  
  50.                                     <input type="email" class="form-control" placeholder="User's Email" name="uEmail" ng-model="uEmail" required autofocus />  
  51.                                 </div>  
  52.                             </div>  
  53.                         </div>  
  54.                         <div class="form-group">  
  55.                             <div class="row">  
  56.                                 <div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">  
  57.                                     Username :  
  58.                                 </div>  
  59.                                 <div class="col-md-6">  
  60.                                     <input type="text" class="form-control" placeholder="Username" name="uName" ng-model="uName" required autofocus />  
  61.                                 </div>  
  62.                             </div>  
  63.                         </div>  
  64.                         <div class="form-group">  
  65.                             <div class="row">  
  66.                                 <div class="col-md-3" style="margin-left: 15px; color: #5bc0de;">  
  67.                                     Password :  
  68.                                 </div>  
  69.                                 <div class="col-md-6">  
  70.                                     <input type="password" class="form-control" placeholder="Password" name="uPwd" ng-model="uPwd" required autofocus />  
  71.                                 </div>  
  72.                             </div>  
  73.                         </div>  
  74.                        <div class="form-group">  
  75.                             <div class="row">  
  76.                                 <div class="col-md-4"></div>  
  77.                                 <div class="col-md-3">  
  78.                                     <input type="button" value="Save" ng-click="SaveUser();" class="btn btn-success" />  
  79.                                 </div>  
  80.                                 <div class="col-md-3">  
  81.                                     @Html.ActionLink("Sign in""Login""Register"new {@class="btn btn-info" })  
  82.                                 </div>  
  83.                             </div>  
  84.                         </div>  
  85.                         <div class="form-group">  
  86.                             <div class="row">  
  87.                                 <div class="col-md-6">  
  88.                                     <div id="divLoading" style="margin: 0px; padding: 0px; position: fixed; right: 0px; top: 0px; width: 100%; height: 100%; background-color: #666666; z-index: 30001; opacity: .8; filter: alpha(opacity=70); display: none">  
  89.                                         <p style="position: absolute; top: 30%; left: 45%; color: White;">  
  90.                                             please wait...<img src="~/Content/images/load.png">  
  91.                                         </p>  
  92.                                     </div>  
  93.                                 </div>  
  94.                             </div>  
  95.                         </div>  
  96.                     </div>  
  97.                 </form>  
  98.             </div>  
  99.         </div>  
  100.     </div>  
  101. </body>  
  102. </html> 
  • As we discussed earlier ,ng-app is a directive that is used to initialize the app with this module.
  • Drag and drop script files in head tag.
  • ng-controller is used with the div tag to initialize with the controller.
  • In the form write code for all the fields.
  • On the Save click call the method SaveUser in controller.js.

     

Change the layout of project
 
  • Find _Layout.cshtml file in the shared folder under views folder.
  • Write code as given below.

     

  1. <!DOCTYPE html>  
  2. <html lang="en">  
  3. <head>  
  4.     <meta charset="utf-8" />  
  5.     <title>@ViewBag.Title</title>  
  6.     <link href="~/favicon.ico" rel="shortcut icon" type="image/x-icon" />  
  7.     <meta name="viewport" content="width=device-width" />  
  8.     <script src="~/Scripts/angular1.2.18.min.js"></script>  
  9.     @Styles.Render("~/css")  
  10. </head>  
  11. <body>  
  12.     <div class="navbar navbar-default navbar-fixed-top">  
  13.         <div class="container">  
  14.             <div class="navbar-header">  
  15.                 <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">  
  16.                     <span class="icon-bar"></span>  
  17.                     <span class="icon-bar"></span>  
  18.                     <span class="icon-bar"></span>  
  19.                 </button>  
  20.                 <a class="navbar-brand" href="#">User Management system</a>  
  21.             </div>  
  22.         </div>  
  23.     </div>  
  24.     <div id="body">  
  25.         @RenderSection("featured", required: false)  
  26.   
  27.         <section class="content-wrapper main-content clear-fix">  
  28.             @RenderBody()  
  29.         </section>  
  30.     </div>  
  31.     @Scripts.Render("~/js")  
  32.     @RenderSection("scripts", required: false)  
  33. </body>  
  34. </html> 
Start your own app

     



Similar Articles