AJAX Requests from jQuery to ASP.NET Core API Losing Authentication

26 views Asked by At

I am developing a feature in my web application that allows authenticated users to submit comments through a form. The frontend uses jQuery for AJAX requests, and the backend is built with ASP.NET Core. Despite the user being authenticated when loading the page, the AJAX request to the server does not seem to carry over the authentication state, resulting in the server treating the request as unauthenticated.

Here's the HTML form used for submission:

<form id="newItemForm">
    <input type="text" id="itemText" placeholder="Your comment" required />
    <button type="submit">Submit</button>
</form>

The jQuery function handling the submission and making the AJAX call:

function addItem(itemText) {
    $.ajax({
        url: '/api/items/' + itemId,
        method: 'POST',
        contentType: 'application/json',
        data: JSON.stringify(itemText),
        success: function () {
            fetchItems();
        },
        error: function (xhr, status, error) {
            alert('An error occurred while submitting your comment.');
        }
    });
}

And the ASP.NET Core controller expecting an authenticated request:

[HttpPost("{Id}")]
[Route("api/[controller]")]
public IActionResult Post(Guid Id, [FromBody] string bodyText)
{
    Guid? userGuid = UserController.GetUserGuid(HttpContext);
    if (userGuid == null)
        return BadRequest("User not logged in. Only for authenticated users");

    string cleanedText = Regex.Replace(bodyText, @"[^\p{L}\p{N}\s,.!?]", "");

    Comments comment = new Comments
    {
        ItemId = Id,
        Comment = cleanedText,
        Userid = (Guid)userGuid
    };

    APIResponse<string> response = CommentRepository.PostNewItem(_context, comment);
    if (response.Success)
        return Ok(response);

    return BadRequest(response);
}
public static Guid? GetUserGuid(HttpContext httpContext)
{
    var userId = httpContext.User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.NameIdentifier)?.Value;
    if (userId != null && Guid.TryParse(userId, out Guid userIdGuid))
    {
        return userIdGuid;
    }
    return null;
}

The user is authenticated on the razor page, but the AJAX request seems to be missing the necessary authentication tokens or headers. I have confirmed the user is indeed authenticated before making the AJAX call, but the authentication does not seem to persist through to the API call.

What steps can I take to ensure that the AJAX request from jQuery is recognized as authenticated by the ASP.NET Core backend, or should I do this in some other way? Is there some other ways of sending this request async in a razor page, wihtout updating the entire page (which a default post method will do)?

EDIT: Added GetUserGuid() method

0

There are 0 answers