How to call a JWT secured APIs with jQuery AJAX [with source codes]

How to call a JWT secured APIs with jQuery AJAX [with source codes]
JWT authentication is a popular standard to highly secure the APIs. In my last tutorial I explained you in full details how to Implement JWT to secure APIs in ASP.NET Core, if you haven’t read it make sure you do it now. In this tutorial I will teach you how to call the APIs that are JWT secured with jQuery AJAX method. The most important thing to note here is that you have to add the JWT Token value on the header of the HTTP request, and prepend the token’s value with the word – Bearer (note the space at the end of the word).

This is shown in the below code:

$.ajax({
    type: "POST",
    url: "https://localhost:44314/Reservation",
    headers: {
        Authorization: 'Bearer ' + token
    },
    dataType: 'json',
    success: function (result, status, xhr) {
        ShowData(result);
    },
    error: function (xhr, status, error) {
         alert(error);
    }
});
API’s signature is given below

I will call the below API with jQuery here:

[HttpGet]
public IEnumerable<Reservation> Get(){

// returns a list of reservations

}

Once this feature is created it will work as shown by the below video:

jwt jquery video

Creating full Client JWT Application in jQuery

Make sure you add IdentityModel.Tokens.Jwt package from NuGet. This package enables you to create JWT tokens in your application.

Next, create a controller called ‘jQueryApiController.cs’ in your project and to it add the following code:

public class jQueryApiController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public string Index(string username, string password)
    {
        if ((username != "Secret") || (password != "Secret"))
            return "Error";

        string tokenString = GenerateJSONWebToken();
        return tokenString;
    }

    private string GenerateJSONWebToken()
    {
        var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MynameisJamesBond007"));
        var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

        var token = new JwtSecurityToken(
            issuer: "https://www.yogihosting.com",
            audience: "https://www.yogihosting.com",
            expires: DateTime.Now.AddHours(3),
            signingCredentials: credentials,
            claims: claims
            );

        return new JwtSecurityTokenHandler().WriteToken(token);
    }

    [HttpPost]
    public IActionResult Reservation([FromBody]List<Reservation> rList)
    {
        return PartialView("Reservation", rList);
    }
} 
Explanation: In the above code you can see that there is an ‘Index’ action method of HTTP Post type. I will call this action with my AJAX code from the View. This action method checks for valid user name & password (here it is word ‘Secret’), and then calls the GenerateJSONWebToken() method to create the JWT token.

There is also a Reservation action that accepts a list of reservations (which is the data returned by the API). It then returns a partial view that shows all these reservations.

You will understand how the API call is made when you see the Views codes.

So create the Index view whose code is given below:

<table class="w-25 table table-striped table-bordered">
    <tbody>
        <tr>
            <td>Username</td>
            <td><input type="text" id="username" name="username" /></td>
        </tr>
        <tr>
            <td>Password</td>
            <td><input type="text" id="password" name="password" /></td>
        </tr>
        <tr>
            <td colspan="2">
                <button id="submit">Submit</button>
            </td>
        </tr>
    </tbody>
</table>

<div id="reservations"></div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
    $(document).ready(function () {
        $("#submit").click(function (e) {
            $.ajax({
                type: "POST",
                url: "@Url.Action("Index")",
                data: {username: $("#username").val(), password: $("#password").val()},
                dataType: "text",
                success: function (result) {
                    if (result != "Error")
                        CallAPI(result);
                    }
                },
                error: function (req, status, error) {
                    alert(error);
                }
            });
        });

        function CallAPI(token) {
            $.ajax({
                type: "GET",
                url: "https://localhost:44314/Reservation",
                headers: {
                    Authorization: 'Bearer ' + token
                },
                dataType: 'json',
                success: function (result, status, xhr) {
                    ShowData(result);
                },
                error: function (xhr, status, error) {
                     alert(error);
                }
            });
        }

        function ShowData(reservations) {
            $.ajax({
                type: "POST",
                contentType: "application/json",
                url: "@Url.Action("Reservation")",
                data: JSON.stringify(reservations),
                success: function (result) {
                    $("#reservations").html(result)
                },
                error: function (req, status, error) {
                    alert(error);
                }
            });
        }
    });
</script>

Explanation: The HTML table is simply for accepting the username and password which here should be the word – ‘Secret’. The screen shot is shown below:

login screen

The div with id reservations will show the reservations returned by the API.

Notice that on the click of the submit button the ‘Index’ action method is called by jQuery (see below code). This method will receive the JWT Token so on the success callback I am calling another jQuery function named ‘CallAPI’ and passing the token to it.

$("#submit").click(function (e) {
    $.ajax({
        type: "POST",
        url: "@Url.Action("Index")",
        data: {username: $("#username").val(), password: 
word").val()},
        dataType: "text",
        success: function (result) {
            if (result != "Error")
                CallAPI(result);
        },
        error: function (req, status, error) {
            alert(error);
        }
    });
});
The CallAPI() function’s code is given below:
function CallAPI(token) {
    $.ajax({
        type: "GET",
        url: "https://localhost:44314/Reservation",
        headers: {
            Authorization: 'Bearer ' + token
        },
        dataType: 'json',
        success: function (result, status, xhr) {
            ShowData(result);
        },
        error: function (xhr, status, error) {
             alert(error);
        }
    });
}

The ‘CallAPI’ method makes the API call and adds the JWT Token to the authorization header like this:

headers: {
    Authorization: 'Bearer ' + token
},

On the success callback it calls another function called ShowData(result) whose task is to show the reservations data in the View.

See the ShowData(result) function’s code given below. It makes AJAX call and calls the ‘Reservation’ action method. The reservation action will return a partial view (partial view is bind with the data returned by the API).

function ShowData(reservations) {
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: "@Url.Action("Reservation")",
        data: JSON.stringify(reservations),
        success: function (result) {
            $("#reservations").html(result)
        },
        error: function (req, status, error) {
            alert(error);
        }
    });
}

Note: It’s success callback is the place where it binds the ‘reservations’ div with this data.

You can download the full codes of this tutorial from the below link:

Download

JWT Token with Claims

JWT Claims are can contain added information to the token. Example – A JWT token contains a claim called Name that asserts that the name of the user who is authenticating is “Bobby”. So in this case the records should refine for the user “Bobby”.

Let me show you how to do this thing. Inside the GenerateJSONWebToken() function create a claim and add it to the token as shown below:

private string GenerateJSONWebToken()
{
    var claims = new[] {
        new Claim("Name", "Bobby"),
        new Claim(JwtRegisteredClaimNames.Email, "[email protected]"),
    };

    var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("MynameisJamesBond007"));
    var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);

    var token = new JwtSecurityToken(
        issuer: "https://www.yogihosting.com",
        audience: "https://www.yogihosting.com",
        expires: DateTime.Now.AddHours(3),
        signingCredentials: credentials,
        claims: claims
        );

    return new JwtSecurityTokenHandler().WriteToken(token);
}
Finally update the API to fetch this claim’s value through the HttpContext.User.Claims class, and then filter out the reservations that matches exactly to the ‘Name’ value assigned on the claim. Check below code:
[HttpGet]
public IEnumerable<Reservation> Get()
{
    var claims = HttpContext.User.Claims;
    return CreateDummyReservations().Where(t => t.Name == claims.FirstOrDefault(c => c.Type == "Name").Value);
}

Check the below video to understand how the filtering works:

JWT claims jQuery
Conclusion
I hope you enjoyed creating this JWT feature. Please share this tutorial with your friends to. Thank you!

Share this article -

yogihosting

ABOUT THE AUTHOR

This article has been written by the Technical Staff of YogiHosting. Check out other articles on "ASP.NET Core, jQuery, EF Core, SEO, jQuery, HTML" and more.

Leave a Reply

Your email address will not be published. Required fields are marked *