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.
Login.html
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="scripts/jquery-1.9.1.min.js"></script>
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <meta charset="utf-8" />
- </head>
- <body>
- <h3>
- Log In
- </h3>
- <div class="container">
- <div class="row">
- <div class="col-lg-3">
- <div class="row">
- <div class="form-group">
-
- Email
-
-
- <input class="form-control" type="text" id="txt_Email" />
-
- </div>
- </div>
- <div class="row">
- <div class="form-group">
-
- Password
-
- <input class="form-control" type="password" id="txt_Pwd" />
-
- </div>
- </div>
- <br />
- <div class="row">
- <button id="Txt_Btn" class="btn btn-default">Login</button>
- </div>
- </div>
- </div>
-
- <br />
- <div class="row">
- <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>
- </div>
-
- </div>
- <script>
- $(document).ready(function () {
- var tokenKey = 'acc_Token'
-
function showError(jqXHR) {
alert(jqXHR.status + ': ' + jqXHR.statusText);
}
- $("#Txt_Btn_API").click(function()
-
- {
- var token = sessionStorage.getItem(tokenKey);
- alert(token);
- var headers = {};
- if (token) {
- headers.Authorization = 'Bearer ' + token;
- }
-
- $.ajax({
- type: 'GET',
- url: 'api/values',
- headers: headers
- }).done(function (data) {
- alert(data);
- sessionStorage.setItem(tokenKey, data.access_token);
- }).fail(showError);
- });
-
- $("#Txt_Btn").click(function () {
-
-
- var loginData = {
- grant_type: 'password',
- username: $("#txt_Email").val(),
- password: $("#txt_Pwd").val(),
- };
-
- $.ajax({
- type: 'POST',
- url: '/Token',
- data: loginData
- }).done(function (data) {
-
-
- sessionStorage.setItem(tokenKey, data.access_token);
- alert("Welcome");
- }).fail(showError);
- });
- });
-
- </script>
- </body>
-
- </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:
- [Authorize]
- public class ValuesController : ApiController
- {
-
-
-
- public string Get()
- {
- var userName = this.RequestContext.Principal.Identity.Name;
- return String.Format("Hello, {0}.", userName);
- }
- }
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.
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="scripts/jquery-1.9.1.min.js"></script>
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <meta charset="utf-8" />
- </head>
- <body>
- <h3>
- Log In
- </h3>
- <div class="container">
- <div class="row">
- <div class="col-lg-3">
- <div class="row">
- <div class="form-group">
-
- Email
-
-
- <input class="form-control" type="text" id="txt_Email" />
-
- </div>
- </div>
- <div class="row">
- <div class="form-group">
-
- Password
-
- <input class="form-control" type="password" id="txt_Pwd" />
-
- </div>
- </div>
- <br />
- <div class="row">
- <button id="Txt_Btn" class="btn btn-default">Login</button>
- </div>
- </div>
- </div>
-
- <br />
- <div class="row">
- <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>
- </div>
-
- </div>
- <script>
- $(document).ready(function () {
- var tokenKey = 'acc_Token'
-
function showError(jqXHR) {
alert(jqXHR.status + ': ' + jqXHR.statusText);
}
- $("#Txt_Btn_API").click(function()
-
- {
- var token = localStorage.getItem(tokenKey);
- alert(token);
- var headers = {};
- if (token) {
- headers.Authorization = 'Bearer ' + token;
- }
-
- $.ajax({
- type: 'GET',
- url: 'api/values',
- headers: headers
- }).done(function (data) {
- alert(data);
- localStorage.setItem(tokenKey, data.access_token);
- }).fail(showError);
- });
-
- $("#Txt_Btn").click(function () {
-
-
- var loginData = {
- grant_type: 'password',
- username: $("#txt_Email").val(),
- password: $("#txt_Pwd").val(),
- };
-
- $.ajax({
- type: 'POST',
- url: '/Token',
- data: loginData
- }).done(function (data) {
-
-
- localStorage.setItem(tokenKey, data.access_token);
- alert("Welcome");
- }).fail(showError);
- });
- });
-
- </script>
- </body>
-
- </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:
- <!DOCTYPE html>
- <html>
- <head>
- <title></title>
- <script src="Scripts/jquery-1.10.2.min.js"></script>
- <script src="scripts/jquery-1.9.1.min.js"></script>
- <link href="Content/bootstrap.min.css" rel="stylesheet" />
- <meta charset="utf-8" />
- </head>
- <body>
- <h3>
- Log In
- </h3>
- <div class="container">
- <div class="row">
- <div class="col-lg-3">
- <div class="row">
- <div class="form-group">
-
- Email
-
-
- <input class="form-control" type="text" id="txt_Email" />
-
- </div>
- </div>
- <div class="row">
- <div class="form-group">
-
- Password
-
- <input class="form-control" type="password" id="txt_Pwd" />
-
- </div>
- </div>
- <br />
- <div class="row">
- <button id="Txt_Btn" class="btn btn-default">Login</button>
- <button id="Txt_Btn_Logout" class="btn btn-default">Log Out</button>
- </div>
- </div>
- </div>
-
- <br />
- <div class="row">
- <button id="Txt_Btn_API" class="btn btn-default">Call authorize action</button>
- </div>
-
- </div>
- <script>
- $(document).ready(function () {
- var tokenKey = 'acc_Token'
-
function showError(jqXHR) {
alert(jqXHR.status + ': ' + jqXHR.statusText);
}
- $("#Txt_Btn_API").click(function()
-
- {
- var token = localStorage.getItem(tokenKey);
- alert(token);
- var headers = {};
- if (token) {
- headers.Authorization = 'Bearer ' + token;
- }
-
- $.ajax({
- type: 'GET',
- url: 'api/values',
- headers: headers
- }).done(function (data) {
- alert(data);
- localStorage.setItem(tokenKey, data.access_token);
- }).fail(showError);
- });
- $("#Txt_Btn_Logout").click(function () {
-
- localStorage.removeItem(tokenKey);
- alert("You have logged out sucessfully!")
- });
- $("#Txt_Btn").click(function () {
-
-
- var loginData = {
- grant_type: 'password',
- username: $("#txt_Email").val(),
- password: $("#txt_Pwd").val(),
- };
-
- $.ajax({
- type: 'POST',
- url: '/Token',
- data: loginData
- }).done(function (data) {
-
-
- localStorage.setItem(tokenKey, data.access_token);
- alert("Welcome");
- }).fail(showError);
- });
- });
-
- </script>
- </body>
-
- </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:
- [Authorize(Users="[email protected]")]
- public string Get()
- {
- var userName = this.RequestContext.Principal.Identity.Name;
- return String.Format("Hello, {0}.", userName);
- }
Now, the above action method can be accessed only by the user->
[email protected], the action accessed by other users.
Result in Browser
Result in Browser
I hope you enjoyed this article. Your valuable feedback, question, or comments about this article are always welcomed.