Simple project on Token based authentication in WEB API 2.0

click here to get full sample project 

Token based authentication

What is token based authentication in web api 2.0?

The general concept behind a token-based authentication system is simple. Allow users to enter their username and password in order to obtain a token which allows them to fetch a specific resource - without using their username and password. Once their token has been obtained, the user can offer the token - which offers access to a specific resource for a time period - to the remote site.

For more explanation on Token based Authentication click here.

 

How to implement token based authentication in ASP.NET Web API using OWIN middleware and Identity framework?

First we need to create some data which will be populate based on authentication.

 

To do this, first we need to create a Register screen where we will register user name and password in the database.

Register.html :

 

Then Code of Register.html page will be look like as below :

<!DOCTYPE html>

<html>

<head>

    <title></title>

    <meta charset="utf-8" />

    <link href="Content/bootstrap.min.css" rel="stylesheet" />

</head>

<body style="padding-top:20px">

    <div class="col-md-10 col-md-offset-1">

        <div class="well">

            <!--This table contains the fields that we want to capture to register a new user-->

            <table class="table table-bordered">

                <thead>

                    <tr class="success">

                        <th colspan="2">

                            New User Registration

                        </th>

                    </tr>

                </thead>

                <tbody>

                    <tr>

                        <td>Email</td>

                        <td><input type="text" id="txtEmail" placeholder="Email" /> </td>

                    </tr>

                    <tr>

                        <td>Password</td>

                        <td>

                            <input type="password" id="txtPassword"

                                   placeholder="Password" />

                        </td>

                    </tr>

                    <tr>

                        <td>Confirm Password</td>

                        <td>

                            <input type="password" id="txtConfirmPassword"

                                   placeholder="Confirm Password" />

                        </td>

                    </tr>

                    <tr class="success">

                        <td colspan="2">

                            <input id="btnRegister" class="btn btn-success"

                                   type="button" value="Register" />

                        </td>

                    </tr>

                </tbody>

            </table>

            <!--Bootstrap modal dialog that shows up when regsitration is successful-->

            <div class="modal fade" tabindex="-1" id="successModal"

                 data-keyboard="false" data-backdrop="static">

                <div class="modal-dialog modal-sm">

                    <div class="modal-content">

                        <div class="modal-header">

                            <button type="button" class="close" data-dismiss="modal">

                                &times;

                            </button>

                            <h4 class="modal-title">Success</h4>

                        </div>

                        <div class="modal-body">

                            <form>

                                <h2 class="modal-title">Registration Successful!</h2>

                            </form>

                        </div>

                        <div class="modal-footer">

                            <button type="button" class="btn btn-success"

                                    data-dismiss="modal">

                                Close

                            </button>

                        </div>

                    </div>

                </div>

            </div>

            <!--Bootstrap alert to display any validation errors-->

            <div id="divError" class="alert alert-danger collapse">

                <a id="linkClose" href="#" class="close">&times;</a>

                <div id="divErrorText"></div>

            </div>

        </div>

    </div>

 

    <script src="Scripts/jquery-1.10.2.min.js"></script>

    <script src="Scripts/bootstrap.min.js"></script>

 

    <script type="text/javascript">

        $(document).ready(function () {

 

            //Close the bootstrap alert

            $('#linkClose').click(function () {

                $('#divError').hide('fade');

            });

 

            // Save the new user details

            $('#btnRegister').click(function () {

                $.ajax({

                    url: '/api/account/register',

                    method: 'POST',

                    data: {

                        email: $('#txtEmail').val(),

                        password: $('#txtPassword').val(),

                        confirmPassword: $('#txtConfirmPassword').val()

                    },

                    success: function () {

                        $('#successModal').modal('show');

                    },

                    error: function (jqXHR) {

                        $('#divErrorText').text(jqXHR.responseText);

                        $('#divError').show('fade');

                    }

                });

            });

        });

    </script>

</body>

</html>

If you see above code, it is under the account controller and register action which is provided by web api default template. Once you will create your user it will save in the database. If there is no any database it will create some table in your default database. 

And Tables will be like below :

 

Identity database tables and their purpose

__MigrationHistory - This table tells us that it is using entity framework

AspNetRoles - Stores roles information. We do not have any roles yet so this table is empty

AspNetUserClaims - We do not have claims either so this table will also be empty

AspNetUserLogins - This table is for third party authentication providers like Twitter, Facebook. Microsoft etc. Information about those logins will be stored in this table

AspNetUserRoles - This is a mapping table which tells us which users are in which roles

AspNetUsers - This table stores the registered users of our application

 

For example, if you want to name the database - DotNetMinds, change the DefaultConnection string as shown below

<add name="DefaultConnection"

  connectionString="Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\ DotNetMinds.mdf;Initial Catalog=UsersDB;Integrated Security=True"

  providerName="System.Data.SqlClient" />

 

With the above change, the connection string in web.config is as shown below

<add name="DefaultConnection"

      connectionString="Data Source=(local);Initial Catalog= DotNetMinds;Integrated Security=True"

      providerName="System.Data.SqlClient" />


Now we will see how to generate a Token from Fidler :