ASP.NET Web API With Entity Framework - Part 4

Before proceeding to this article, please go through my previous articles:

In this article I am going to use the UI for explaining the token based individual authentication and authorization in ASP.NET Web API. Get the details about how to create an individual authentication template in ASP.NET Web API here.

In my previous article I have explained token based authentication using POST MAN tool, now we are going to create a UI to do those operations

Let us start with Registration:

         1. Create an HTML page in the project which we created in part-3 and name it Register.html

      /api/account/Register is the API used for registration

Register.html 

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  6.     <script src="scripts/jquery-1.9.1.min.js"></script>  
  7.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  8.     <meta charset="utf-8" />  
  9. </head>  
  10. <body>  
  11.     <div class="container">  
  12.         <div class="row">  
  13.             <h3>Registration</h3>  
  14.             <br>  
  15.             <div class="col-lg-4">  
  16.                  
  17.                 <div class="row">  
  18.                     <div class="form-group">  
  19.   
  20.                         <label style=> Email/UserName</label>  
  21.   
  22.   
  23.                         <input class="form-control" type="text" id="txt_Email" />  
  24.   
  25.                     </div>  
  26.                 </div>  
  27.                 <div class="row">  
  28.                     <div class="form-group">  
  29.   
  30.                         Password  
  31.   
  32.                         <input class="form-control" type="password" id="txt_Pwd" />  
  33.   
  34.                     </div>  
  35.                 </div>  
  36.                 <div class="row">  
  37.                     <div class="form-group">  
  38.   
  39.                        Confirm Password  
  40.   
  41.                         <input class="form-control" type="password" id="txt_Confirm_Pwd" />  
  42.   
  43.                     </div>  
  44.                 </div>  
  45.                 <br />  
  46.                 <div class="row">  
  47.                     <button id="Txt_Btn" onclick="Btn_click()" class="btn btn-default">Register</button>  
  48.                 </div>  
  49.             </div>  
  50.         </div>  
  51.   
  52.           
  53.   
  54.     </div>  
  55.     <script>  
  56.         $(document).ready(function () {  
  57.              
             function showError(jqXHR) {
                alert(jqXHR.status + ': ' + jqXHR.statusText);
                                  }
  58.             $("#Txt_Btn").click(function () {  
  59.                 var data = {  
  60.                     Email: $("#txt_Email").val(),  
  61.                     Password: $("#txt_Pwd").val(),  
  62.                     ConfirmPassword: $("#txt_Confirm_Pwd").val(),  
  63.   
  64.                 };  
  65.                 $.ajax({  
  66.                     type: 'POST',  
  67.                     url: '/api/Account/Register' 
  68.                     contentType: 'application/json; charset=utf-8',  
  69.                     data: JSON.stringify(data)  
  70.                 }).done(function (data) {  
  71.                     alert("Registration Sucessfull!")  
  72.                 }).fail(showError);  
  73.             })  
  74.     })  
  75.     </script>  
  76. </body>  
  77. </html>  

Result in Browser

 

HTTP POST request Params

 

Record successfully stored in the table

   

            2.
Create one more HTML page in the project and name it Login.html,

Login.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  6.     <script src="scripts/jquery-1.9.1.min.js"></script>  
  7.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  8.     <meta charset="utf-8" />  
  9. </head>  
  10. <body>  
  11.     <h3>  
  12.         Log In  
  13.     </h3>  
  14.     <div class="container">  
  15.         <div class="row">  
  16.             <div class="col-lg-3">  
  17.                 <div class="row">  
  18.                     <div class="form-group">  
  19.   
  20.                         Email  
  21.                      
  22.                       
  23.                         <input class="form-control" type="text" id="txt_Email" />  
  24.   
  25.                     </div>  
  26.                 </div>  
  27.                 <div class="row">  
  28.                     <div class="form-group">  
  29.   
  30.                         Password  
  31.                     
  32.                         <input class="form-control" type="password" id="txt_Pwd" />  
  33.   
  34.                     </div>  
  35.                 </div>  
  36.                 <br />  
  37.                 <div class="row">  
  38.                     <button id="Txt_Btn"  class="btn btn-default">Login</button>  
  39.                 </div>  
  40.             </div>  
  41.         </div>  
  42.          
  43.             <br />  
  44.             <div class="row">  
  45.                 <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>  
  46.             </div>  
  47.           
  48.     </div>  
  49.     <script>  
  50.         $(document).ready(function () {   
  51.             var tokenKey = 'acc_Token'  
  52.              
                function showError(jqXHR) {
                      alert(jqXHR.status + ': ' + jqXHR.statusText);
                         }
  53.             $("#Txt_Btn_API").click(function()  
  54.              
  55.             {  
  56.             var token = sessionStorage.getItem(tokenKey);  
  57.             alert(token);  
  58.             var headers = {};  
  59.             if (token) {  
  60.                 headers.Authorization = 'Bearer ' + token;  
  61.             }  
  62.   
  63.             $.ajax({  
  64.                 type: 'GET',  
  65.                 url: 'api/values',  
  66.                 headers: headers  
  67.             }).done(function (data) {  
  68.                 alert(data);  
  69.                 sessionStorage.setItem(tokenKey, data.access_token);  
  70.             }).fail(showError);  
  71.         });  
  72.   
  73.             $("#Txt_Btn").click(function () {  
  74.           
  75.               
  76.             var loginData = {  
  77.                 grant_type: 'password',  
  78.                 username: $("#txt_Email").val(),  
  79.                 password: $("#txt_Pwd").val(),  
  80.             };  
  81.   
  82.             $.ajax({  
  83.                 type: 'POST',  
  84.                 url: '/Token',  
  85.                 data: loginData  
  86.             }).done(function (data) {  
  87.                 
  88.                 // Cache the access token in session storage.   
  89.                 sessionStorage.setItem(tokenKey, data.access_token);  
  90.                 alert("Welcome");  
  91.             }).fail(showError);  
  92.         });  
  93.         });  
  94.   
  95.     </script>  
  96. </body>  
  97.   
  98. </html>  

Enter the Email and the password and hit login button,

Result in Browser
 
  

Now we are successfully logged in using Token End Point, The response of the Token request to Login as a user. 
 

It's time to access the authorize action methods in the application, For example, consider the following authorize action method which is in ValuesController:

  1. [Authorize]  
  2.      public class ValuesController : ApiController  
  3.     {  
  4.         // GET api/values  
  5.   
  6.    
  7.         public  string Get()  
  8.         {  
  9.             var userName = this.RequestContext.Principal.Identity.Name;  
  10.             return String.Format("Hello, {0}.", userName);  
  11.         }  
  12. }  
Now our token is stored as session storage, so now we can access the authorize action in the application. Click on the call authorize action button in the login.html which will call the above action method using api/values API with Token as a header 
 
Result in Browser
 
 
 
Header of the GET: api/values request,
 
 
 
Response of the GET:api/values API, 
 
  

Since we are using the session storage the token will be stored till the page session expires, if we have opened the application in separate tab/window in browser then our token will be cleared.

Calling the api/values API in new tab/window.
 
 
 
 
 
 

Using Local Storage:

Login.html

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  6.     <script src="scripts/jquery-1.9.1.min.js"></script>  
  7.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  8.     <meta charset="utf-8" />  
  9. </head>  
  10. <body>  
  11.     <h3>  
  12.         Log In  
  13.     </h3>  
  14.     <div class="container">  
  15.         <div class="row">  
  16.             <div class="col-lg-3">  
  17.                 <div class="row">  
  18.                     <div class="form-group">  
  19.   
  20.                         Email  
  21.                      
  22.                       
  23.                         <input class="form-control" type="text" id="txt_Email" />  
  24.   
  25.                     </div>  
  26.                 </div>  
  27.                 <div class="row">  
  28.                     <div class="form-group">  
  29.   
  30.                         Password  
  31.                     
  32.                         <input class="form-control" type="password" id="txt_Pwd" />  
  33.   
  34.                     </div>  
  35.                 </div>  
  36.                 <br />  
  37.                 <div class="row">  
  38.                     <button id="Txt_Btn"  class="btn btn-default">Login</button>  
  39.                 </div>  
  40.             </div>  
  41.         </div>  
  42.          
  43.             <br />  
  44.             <div class="row">  
  45.                 <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>  
  46.             </div>  
  47.           
  48.     </div>  
  49.     <script>  
  50.         $(document).ready(function () {   
  51.             var tokenKey = 'acc_Token'  
  52.                  
                         function showError(jqXHR) {
                                  alert(jqXHR.status + ': ' + jqXHR.statusText);
                               }
  53.             $("#Txt_Btn_API").click(function()  
  54.              
  55.             {  
  56.             var token = localStorage.getItem(tokenKey);  
  57.             alert(token);  
  58.             var headers = {};  
  59.             if (token) {  
  60.                 headers.Authorization = 'Bearer ' + token;  
  61.             }  
  62.   
  63.             $.ajax({  
  64.                 type: 'GET',  
  65.                 url: 'api/values' 
  66.                 headers: headers  
  67.             }).done(function (data) {  
  68.                 alert(data);  
  69.                 localStorage.setItem(tokenKey, data.access_token);  
  70.             }).fail(showError);  
  71.         });  
  72.   
  73.             $("#Txt_Btn").click(function () {  
  74.           
  75.               
  76.             var loginData = {  
  77.                 grant_type: 'password',  
  78.                 username: $("#txt_Email").val(),  
  79.                 password: $("#txt_Pwd").val(),  
  80.             };  
  81.   
  82.             $.ajax({  
  83.                 type: 'POST',  
  84.                 url: '/Token',  
  85.                 data: loginData  
  86.             }).done(function (data) {  
  87.                 
  88.                 // Cache the access token in local storage.   
  89.                 localStorage.setItem(tokenKey, data.access_token);  
  90.                 alert("Welcome");  
  91.             }).fail(showError);  
  92.         });  
  93.         });  
  94.   
  95.     </script>  
  96. </body>  
  97.   
  98. </html>  
Result in Browser
 
 
When the page is accessed in separate tab/window,
 
 
 

By using local storage the token is stored locally in the browser and it will persist till the token is removed from the local browser memory.

Logout:

HTML Code:

  1. <!DOCTYPE html>  
  2. <html>  
  3. <head>  
  4.     <title></title>  
  5.     <script src="Scripts/jquery-1.10.2.min.js"></script>  
  6.     <script src="scripts/jquery-1.9.1.min.js"></script>  
  7.     <link href="Content/bootstrap.min.css" rel="stylesheet" />  
  8.     <meta charset="utf-8" />  
  9. </head>  
  10. <body>  
  11.     <h3>  
  12.         Log In  
  13.     </h3>  
  14.     <div class="container">  
  15.         <div class="row">  
  16.             <div class="col-lg-3">  
  17.                 <div class="row">  
  18.                     <div class="form-group">  
  19.   
  20.                         Email  
  21.                      
  22.                       
  23.                         <input class="form-control" type="text" id="txt_Email" />  
  24.   
  25.                     </div>  
  26.                 </div>  
  27.                 <div class="row">  
  28.                     <div class="form-group">  
  29.   
  30.                         Password  
  31.                     
  32.                         <input class="form-control" type="password" id="txt_Pwd" />  
  33.   
  34.                     </div>  
  35.                 </div>  
  36.                 <br />  
  37.                 <div class="row">  
  38.                     <button id="Txt_Btn"  class="btn btn-default">Login</button>  
  39.                     <button id="Txt_Btn_Logout" class="btn btn-default">Log Out</button>  
  40.                 </div>  
  41.             </div>  
  42.         </div>  
  43.          
  44.             <br />  
  45.             <div class="row">  
  46.                 <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>  
  47.             </div>  
  48.           
  49.     </div>  
  50.     <script>  
  51.         $(document).ready(function () {   
  52.             var tokenKey = 'acc_Token'  
  53.   
                   function showError(jqXHR) {
                         alert(jqXHR.status + ': ' + jqXHR.statusText);
                               }
  54.             $("#Txt_Btn_API").click(function()  
  55.              
  56.             {  
  57.             var token = localStorage.getItem(tokenKey);  
  58.             alert(token);  
  59.             var headers = {};  
  60.             if (token) {  
  61.                 headers.Authorization = 'Bearer ' + token;  
  62.             }  
  63.   
  64.             $.ajax({  
  65.                 type: 'GET',  
  66.                 url: 'api/values',  
  67.                 headers: headers  
  68.             }).done(function (data) {  
  69.                 alert(data);  
  70.                 localStorage.setItem(tokenKey, data.access_token);  
  71.             }).fail(showError);  
  72.         });  
  73.             $("#Txt_Btn_Logout").click(function () {  
  74.                   
  75.                 localStorage.removeItem(tokenKey);  
  76.                 alert("You have logged out sucessfully!")  
  77.             });  
  78.             $("#Txt_Btn").click(function () {  
  79.           
  80.               
  81.             var loginData = {  
  82.                 grant_type: 'password',  
  83.                 username: $("#txt_Email").val(),  
  84.                 password: $("#txt_Pwd").val(),  
  85.             };  
  86.   
  87.             $.ajax({  
  88.                 type: 'POST',  
  89.                 url: '/Token',  
  90.                 data: loginData  
  91.             }).done(function (data) {  
  92.                 
  93.                 // Cache the access token in local storage.   
  94.                 localStorage.setItem(tokenKey, data.access_token);  
  95.                 alert("Welcome");  
  96.             }).fail(showError);  
  97.         });  
  98.         });  
  99.   
  100.     </script>  
  101. </body>  
  102.   
  103. </html>  
From the above code it is clear that the logout function will remove the token from the local storage using remove Item function.
 
Result in Browser
 
 

Authorization based on user

For example, consider the following authorize action method which is in values controller: 

  1. [Authorize(Users="[email protected]")]  
  2.         public  string Get()  
  3.         {  
  4.             var userName = this.RequestContext.Principal.Identity.Name;  
  5.             return String.Format("Hello, {0}.", userName);  
  6.         }  
Now, the above action method can be accessed only by the user->[email protected], the action accessed by other users.
 
Result in Browser

 
 
The action accessed by the user [email protected],
 
Result in Browser
 
 
 
I hope you enjoyed this article. Your valuable feedback, question, or comments about this article are always welcomed.  


Similar Articles