(C# ASP.NET Core Ajax) Authentication and Authorization with AJAX Requests

In brief: Just two additions are required to implement AJAX based authorization in your existing ASP.NET Core application - first is on the javascript side - where the response code should be tested, and second on the server side where User.IsInRole has to be tested. The concept is explained in the text that follows, and a working example is described in the appended youtube video!
(Rev. 19-Mar-2024)

Categories | About |     |  

Parveen,

Your server side handler has to check the authorization status by testing for the condition: User.IsInRole("Admn-or-whatever"). If it verifies the caller as un-authorized, then a status code of 403 or 401 can be sent by setting the property StatusCode like this: new JsonResult("Error") { StatusCode = 403}, otherwise, JsonResult can be returned as usual return new JsonResult("data-whatever"). The default StatusCode is HTTP OK 200 in the latter case.

And on the client side: javascript can be used to read the response code and make a redirect to the login page, as explained in the code example next.

Client Side Javascript

Following is a schematic of how to do it when using the javascript fetch method. It is assumed that the server responds with 403 when authorization fails.

// relevant part of the code shown 
fetch(url,
  {
    method: "GET"
  }
)
  // if any exceptions - log them 
  .catch(err => console.log("network error: " + err))

  .then(response => {

    // ***************************** 
    // this is the crux 
    if (403 == response.status) {

      location.href = "/Login";

      return;

    }
    // ***************************** 

    // read json from the response stream 
    response.json().then(data => {

      // do whatever with data 

    });

Video Explanation

Please watch, write your comments and discussion on the following youtube video:

Server Side Handler

This is an extract of the server side handler. It is assumed that there is a GetReportID function that returns the report.

// code of the IndexModel class 
public async Task<JsonResult> OnGetRep(string id)
{

  // artificial delay 
  await Task.Delay(500);

  if (!User.IsInRole("User"))
  {

    return new JsonResult("No-Auth")
    {

      StatusCode = 403
    };

  }

  // get report from database 
  String report = GetReportForID(id);

  return new JsonResult(report);

}


This Blog Post/Article "(C# ASP.NET Core Ajax) Authentication and Authorization with AJAX Requests" by Parveen is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.