अजपा योग क्रिया आणि ध्यान : श्वास, मंत्र, मुद्रा आणि ध्यान यांच्या सहाय्याने मनःशांती, एकाग्रता, चक्र संतुलन आणि कुंडलिनी जागृती. अधिक माहिती आणि आगामी तारखांसाठी येथे जा.


JWT Authentication in ASP.NET Core using jQuery Client

In my previous article we discussed what JWT authentication is and how to implement it in ASP.NET Core APIs. In that article you learnt to use Postman tool to test the JWT functionality. In most of the real-world cases you will be handling the JWT using either client side script (jQuery, Angular etc.) or server side code (HttpClient component). To that end this article discusses using jQuery to consume the SecurityController and EmployeeController we developed earlier.

Rather than building a full-fledge client application that allows you to log in and call the API, we will build a simple jQuery client as shown below:

As you can see the page has three buttons at the top - Sign In, Sign Out, and Show Data. Clicking on the Sign In button calls the SecurityController API and grabs the JWT token returned by the service. Clicking on the Sign Out button removes the JWT token from the client side. And clicking on the Show Data button calls the Employee API. The data returned by the Employee API is shown in a table.

Ok. Let's get going.

Open the same project you developed last time. Then add HomeController and Index view to it as you normally do for any ASP.NET Core MVC project. Then add the following markup in the Index view.

<body>
  <button type="button" id="login">Sign In</button>
  <button type="button" id="logout">Sign Out</button>
  <button type="button" id="showData">Show Data</button>
  <div id="response"></div>
</body>

The three buttons mentioned earlier have IDs - login, logout, and showData. The response <div> shows the response from the API calls. The response could be success / error message or employee data.

Then add a <script> reference to the jQuery library in the page like so:

<script src="~/jquery.min.js"></script>

Then add a new <script> block and write the following skeleton code in it.

$(document).ready(function () {

    $("#login").click(function () {

    });

    $("#showData").click(function () {

    });

    $("#logout").click(function () {

    });
});

The code consists of three event handler functions for dealing with the three buttons.

Let's complete each handler one-by-one.

The following code shows the Sign In button's click event handler.

$("#login").click(function () {

    var options = {};
    options.url = "/api/security";
    options.type = "POST";

    var obj = {};

    obj.userName = "User1";
    obj.password = "pass$word";

    options.data = JSON.stringify(obj);
    options.contentType = "application/json";
    options.dataType = "json";

    options.success = function (obj) {
        sessionStorage.setItem("token", obj.token);
        $("#response").html("<h2>User 
successfully logged in.</h2>");
    };
    options.error = function () {
        $("#response").html("<h2>Error while 
calling the Web API!</h2>");
    };
    $.ajax(options);
});

The above code makes a POST request to the Security API. Recollect that the Security API has Login() action that accepts a UserName and Password. These credentials are supplied using JavaScript object and the data property of options object.

The success function receives the Ok response along with the JWT token. The important thing is this - we need to preserve the JWT token returned by the Security API somehow. There could be different ways to do that such as hidden form field, localStorage, or sessionStorage. Here, I am using sessionStorage so that the JWT token is not permanently stored on the client machine. As soon as the browser is closed the sessionStorage and hence the token gets destroyed.

Finally, we use $.ajax() method to initiate the Ajax call to the Security API.

Depending on whether the Security API call is successful or not we display a success or error message in the response <div> element. A sample successful run of the page is shown below:

Now let's discuss the Show Data functionality.

$("#showData").click(function () {
    var options = {};
    options.url = "/api/employee";
    options.type = "GET";
    options.beforeSend = function (request) {
        request.setRequestHeader("Authorization", 
"Bearer " + sessionStorage.getItem("token"));
    };
    options.dataType = "json";
    options.success = function (data) {
        var table = "<table border='1' cellpadding='10'>";
        data.forEach(function (element) {
            var row = "<tr>";
            row += "<td>";
            row += element.employeeID;
            row += "</td>";
            row += "<td>";
            row += element.firstName;
            row += "</td>";
            row += "<td>";
            row += element.lastName;
            row += "</td>";
            row += "</tr>";
            table += row;
        });
        table += "</table>";
        $("#response").append(table);
    };
    options.error = function (a,b,c) {
        $("#response").html("<h2>Error while 
calling the Web API! (" + b + " - " + c + ")</h2>");
    };
    $.ajax(options);
});

The Show Data event handler makes a request  to the Employee API using GET verb. What is important while making this call is to pass the JWT token issued earlier to the secured Employee API. To accomplish this task we use beforeSend function and add the Authorization HTTP header to the request.

The success function receives the employee array of objects and renders it into a table as shown in the beginning of this article. The error function displays the error message in the response <div> element. The following figure shows a sample erroneous run of the page when you try to call Employee API without signing in.

The Sign Out functionality is quite straightforward. You simply need to remove the JWT token from the sessionStorage as shown below:

$("#logout").click(function () {
    sessionStorage.removeItem("token");
    $("#response").html("<h2>User successfully 
logged out.</h2>");
});

That's it for now! Keep coding!!


Bipin Joshi is an independent software consultant and trainer by profession specializing in Microsoft web development technologies. Having embraced the Yoga way of life he is also a meditation teacher and spiritual guide to his students. He is a prolific author and writes regularly about software development and yoga on his websites. He is programming, meditating, writing, and teaching for over 27 years. To know more about his ASP.NET online courses go here. More details about his Ajapa Japa and Shambhavi Mudra online course are available here.

Posted On : 28 January 2019