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. <div class="row">
  17. <div class="form-group">
  18. <label style=> Email/UserName</label>
  19. <input class="form-control" type="text" id="txt_Email" />
  20. </div>
  21. </div>
  22. <div class="row">
  23. <div class="form-group">
  24. Password
  25. <input class="form-control" type="password" id="txt_Pwd" />
  26. </div>
  27. </div>
  28. <div class="row">
  29. <div class="form-group">
  30. Confirm Password
  31. <input class="form-control" type="password" id="txt_Confirm_Pwd" />
  32. </div>
  33. </div>
  34. <br />
  35. <div class="row">
  36. <button id="Txt_Btn" onclick="Btn_click()" class="btn btn-default">Register</button>
  37. </div>
  38. </div>
  39. </div>
  40. </div>
  41. <script>
  42. $(document).ready(function () {
  43. function showError(jqXHR) {
    alert(jqXHR.status + ': ' + jqXHR.statusText);
    }
  44. $("#Txt_Btn").click(function () {
  45. var data = {
  46. Email: $("#txt_Email").val(),
  47. Password: $("#txt_Pwd").val(),
  48. ConfirmPassword: $("#txt_Confirm_Pwd").val(),
  49. };
  50. $.ajax({
  51. type: 'POST',
  52. url: '/api/Account/Register',
  53. contentType: 'application/json; charset=utf-8',
  54. data: JSON.stringify(data)
  55. }).done(function (data) {
  56. alert("Registration Sucessfull!")
  57. }).fail(showError);
  58. })
  59. })
  60. </script>
  61. </body>
  62. </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. Email
  20. <input class="form-control" type="text" id="txt_Email" />
  21. </div>
  22. </div>
  23. <div class="row">
  24. <div class="form-group">
  25. Password
  26. <input class="form-control" type="password" id="txt_Pwd" />
  27. </div>
  28. </div>
  29. <br />
  30. <div class="row">
  31. <button id="Txt_Btn" class="btn btn-default">Login</button>
  32. </div>
  33. </div>
  34. </div>
  35. <br />
  36. <div class="row">
  37. <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>
  38. </div>
  39. </div>
  40. <script>
  41. $(document).ready(function () {
  42. var tokenKey = 'acc_Token'
  43. function showError(jqXHR) {
    alert(jqXHR.status + ': ' + jqXHR.statusText);
    }
  44. $("#Txt_Btn_API").click(function()
  45. {
  46. var token = sessionStorage.getItem(tokenKey);
  47. alert(token);
  48. var headers = {};
  49. if (token) {
  50. headers.Authorization = 'Bearer ' + token;
  51. }
  52. $.ajax({
  53. type: 'GET',
  54. url: 'api/values',
  55. headers: headers
  56. }).done(function (data) {
  57. alert(data);
  58. sessionStorage.setItem(tokenKey, data.access_token);
  59. }).fail(showError);
  60. });
  61. $("#Txt_Btn").click(function () {
  62. var loginData = {
  63. grant_type: 'password',
  64. username: $("#txt_Email").val(),
  65. password: $("#txt_Pwd").val(),
  66. };
  67. $.ajax({
  68. type: 'POST',
  69. url: '/Token',
  70. data: loginData
  71. }).done(function (data) {
  72. // Cache the access token in session storage.
  73. sessionStorage.setItem(tokenKey, data.access_token);
  74. alert("Welcome");
  75. }).fail(showError);
  76. });
  77. });
  78. </script>
  79. </body>
  80. </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. public string Get()
  6. {
  7. var userName = this.RequestContext.Principal.Identity.Name;
  8. return String.Format("Hello, {0}.", userName);
  9. }
  10. }
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. Email
  20. <input class="form-control" type="text" id="txt_Email" />
  21. </div>
  22. </div>
  23. <div class="row">
  24. <div class="form-group">
  25. Password
  26. <input class="form-control" type="password" id="txt_Pwd" />
  27. </div>
  28. </div>
  29. <br />
  30. <div class="row">
  31. <button id="Txt_Btn" class="btn btn-default">Login</button>
  32. </div>
  33. </div>
  34. </div>
  35. <br />
  36. <div class="row">
  37. <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>
  38. </div>
  39. </div>
  40. <script>
  41. $(document).ready(function () {
  42. var tokenKey = 'acc_Token'
  43. function showError(jqXHR) {
    alert(jqXHR.status + ': ' + jqXHR.statusText);
    }
  44. $("#Txt_Btn_API").click(function()
  45. {
  46. var token = localStorage.getItem(tokenKey);
  47. alert(token);
  48. var headers = {};
  49. if (token) {
  50. headers.Authorization = 'Bearer ' + token;
  51. }
  52. $.ajax({
  53. type: 'GET',
  54. url: 'api/values',
  55. headers: headers
  56. }).done(function (data) {
  57. alert(data);
  58. localStorage.setItem(tokenKey, data.access_token);
  59. }).fail(showError);
  60. });
  61. $("#Txt_Btn").click(function () {
  62. var loginData = {
  63. grant_type: 'password',
  64. username: $("#txt_Email").val(),
  65. password: $("#txt_Pwd").val(),
  66. };
  67. $.ajax({
  68. type: 'POST',
  69. url: '/Token',
  70. data: loginData
  71. }).done(function (data) {
  72. // Cache the access token in local storage.
  73. localStorage.setItem(tokenKey, data.access_token);
  74. alert("Welcome");
  75. }).fail(showError);
  76. });
  77. });
  78. </script>
  79. </body>
  80. </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. Email
  20. <input class="form-control" type="text" id="txt_Email" />
  21. </div>
  22. </div>
  23. <div class="row">
  24. <div class="form-group">
  25. Password
  26. <input class="form-control" type="password" id="txt_Pwd" />
  27. </div>
  28. </div>
  29. <br />
  30. <div class="row">
  31. <button id="Txt_Btn" class="btn btn-default">Login</button>
  32. <button id="Txt_Btn_Logout" class="btn btn-default">Log Out</button>
  33. </div>
  34. </div>
  35. </div>
  36. <br />
  37. <div class="row">
  38. <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>
  39. </div>
  40. </div>
  41. <script>
  42. $(document).ready(function () {
  43. var tokenKey = 'acc_Token'
  44. function showError(jqXHR) {
    alert(jqXHR.status + ': ' + jqXHR.statusText);
    }
  45. $("#Txt_Btn_API").click(function()
  46. {
  47. var token = localStorage.getItem(tokenKey);
  48. alert(token);
  49. var headers = {};
  50. if (token) {
  51. headers.Authorization = 'Bearer ' + token;
  52. }
  53. $.ajax({
  54. type: 'GET',
  55. url: 'api/values',
  56. headers: headers
  57. }).done(function (data) {
  58. alert(data);
  59. localStorage.setItem(tokenKey, data.access_token);
  60. }).fail(showError);
  61. });
  62. $("#Txt_Btn_Logout").click(function () {
  63. localStorage.removeItem(tokenKey);
  64. alert("You have logged out sucessfully!")
  65. });
  66. $("#Txt_Btn").click(function () {
  67. var loginData = {
  68. grant_type: 'password',
  69. username: $("#txt_Email").val(),
  70. password: $("#txt_Pwd").val(),
  71. };
  72. $.ajax({
  73. type: 'POST',
  74. url: '/Token',
  75. data: loginData
  76. }).done(function (data) {
  77. // Cache the access token in local storage.
  78. localStorage.setItem(tokenKey, data.access_token);
  79. alert("Welcome");
  80. }).fail(showError);
  81. });
  82. });
  83. </script>
  84. </body>
  85. </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.