Failure to transfer cookie in following requests

I have encountered an issue while attempting to pass a cookie for subsequent AJAX requests to my Spring MVC controller.

For example, I have an /login endpoint where I send JSON via POST method to set a cookie. After setting the cookie, I can see it in Firebug:

The cookie is being created like this:

NewCookie cookie = new NewCookie(new Cookie(SECURITY_TICKET, encodedTicket, configKey, null), null, (int) TimeUnit.MINUTES.toSeconds(expireTime), expireTimeDate, false, false)

And then added to the HTTP headers:

httpHeaders.add(HttpHeaders.SET_COOKIE, cookie.toString());

These headers are then included in the ResponseEntity like so:

ResponseEntity entity = new ResponseEntity<>(this.entity, this.httpHeaders, this.status)

This response entity is returned as my controller's methods are all REST based.

However, when trying to access another (/search) endpoint post successful login, which requires the cookie, the request fails as the cookie is not being passed back.

My AJAX calls are structured like this:

$(function () {
    $.ajax({
        url: 'http://localhost:8080/dev-citigroup-citi/login',
        type: 'POST',
        dataType: 'json',
        data: '{ "username": "client1", "password": "*******", "platform": "iOS", "UUID": "321321321", "application": "CitiReach", "applicationVersion": "1.0" }',
        success: function (data, status, xhr) {
            $.ajax({
                url: 'http://localhost:8080/dev-citigroup-citi/search/eventattendee?q=*:*&start=0&rows=1&wt=json&indent=true',
                type: 'GET',
                xhrFields: { withCredentials:true },
                success: function (data, status, xhr) {
                    console.log(data);
                },
                error: function (jqXHR) {
                    console.log(jqXHR);
                }
            });
        },
        error: function (jqXHR) {
            console.log(jqXHR);
        }
    });
});

Although the /login call works fine, the other one fails. Despite adding

xhrFields: { withCredentials:true }
, the cookie does not seem to be included in the /search request.

I have also correctly configured CORS:

Access-Control-Allow-Origin: http://localhost:63342
Access-Control-Allow-Credentials: true

http://localhost:63342 is the specified origin for the CORS headers.

Any insights on what might be the issue here?

Answer №1

After some investigation, I managed to find the solution by setting

xhrFields: { withCredentials:true }
globally instead of on a method level:

    $.ajaxSetup({
        xhrFields: {
            withCredentials: true
        }
    });

Now, the cookie is successfully passed in all subsequent requests. It's strange why it didn't work when set on the method level, possibly an issue with jQuery version 2.1.3.

This tweak might be beneficial for someone facing a similar problem in the future.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

XMLHttpRequest encounters issues with 'Access-Control-Allow-Origin'

I have developed a JavaScript file that tracks and saves the coordinates of mouse clicks on a web page using an AJAX call. In one website (domain2), I have included the following code in the head section: <script src="http://www.domain1.com/scan/track/ ...

Press the jQuery button to reset all input fields

I have created a table with input fields where class teachers can store their students' data for the principal to review. Each row in the table contains an update and reset button, allowing teachers to save or clear the information entered in the fiel ...

A guide to modifying the color of the Menu component in material-ui

Currently, I am utilizing the Menu component from material-ui and facing an issue while trying to modify the background color. The problem arises when I attempt to apply a color to the Menu, as it ends up altering the entire page's background once the ...

The functionality of jQuery slideDown() seems to be malfunctioning, while fadeIn() operates smoothly

I am having trouble getting the slideDown function to work properly. I have a div where I append some data from a PHP query, and I want to use slideDown to show it in a smooth animation. However, when I try to use slideDown, the content just appears withou ...

The method of implementing an index signature within TypeScript

I'm currently tackling the challenge of using reduce in Typescript to calculate the total count of incoming messages. My struggle lies in understanding how to incorporate an index signature into my code. The error message that keeps popping up states: ...

AngularJS using the ng-controller directive

I am presenting the following HTML code excerpt... <!DOCTYPE html> <html lang="en-US" ng-app> <head> <title>priklad00007</title> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angula ...

What is the best way to identify and interact with a div element using Selenium WebDriver?

Is it possible to select a div id instead of an element id in Selenium WebDriver when working with Java? Below is the HTML code I am currently using: <div id="ui-datepicker-div" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-co ...

Flot seems to be having difficulty uploading JSON files

I am relatively new to working with json and flot, but have been tasked with creating a chart. Can someone please help me troubleshoot why my code is not functioning as expected? $.getJSON('chart.json', function(graphData){ alert(graphData); ...

Ways to resolve the issue of a website displaying with extra whitespace at the bottom

Seeking assistance to resolve the issue with a blank space at the bottom of the web page. Refer to: http://www.khohanghoa.com I have dedicated the entire day to search for a solution and attempted to fix the problem. I have attempted to configure the CS ...

Transferring information to a click event handler in jQuery

My query is about a simple span that looks like this: <span class="action removeAction">Remove</span> These spans are included within a table where each row has a remove span. When one of these spans is clicked, I need to call a URL using AJ ...

Troubleshoot Nested Array URL Parameter Problems in Node.js

I am encountering an issue with extracting data from an array that I am sending to my API through an AXIOS call to Express. The call is sent successfully, but the issue arises when trying to access the data in the property_features parameter. Even though m ...

Extracting the message part from an SMS PDU format: a guide

Is there a way to extract a message from SMS PDU? I'm trying to extract a message from SMS PDU. Online services seem to work fine for this task. For example, at this link - - the message from PDU 0791448720003023240DD0E474D81C0EBB0100001110113152140 ...

What is the best way to asynchronously load an external javascript file in a popup.html file?

I have successfully implemented all the necessary functionalities, but I noticed a delay in loading the popup.html after adding an external javascript file. This file is only a few lines long, so the delay is quite frustrating. To eliminate this lag, I be ...

The comparison between form submission and AJAX request when transmitting data in JSON format

Working on a complex PHP/Drupal project, our team is facing the challenge of enabling a deep link into a page that requires extensive data to be passed from the originating site. We have full control over both ends so cross-domain issues are not a concern ...

When transitioning between forms, I encounter empty values

Currently, I am using JSP and AJAX to extract data from my database and display it in a table. So far, I can retrieve data using any single field without any issues. However, the problem arises when trying to utilize two or more fields simultaneously, resu ...

Query in SQL to retrieve numbers that are multiples of a specified value

To create a candlestick graph, I need to convert the following table: amount created_at updated_at 258 2019-10-17 01:45:17 2019-10-17 01:45:17 186 2019-10-17 01:45:17 2019-10-17 01:45:17 122 2019-10-17 01:46:31 2019-1 ...

A solution for the "header is null" error in a JavaScript website header hide on scroll down function

Trying to enable a show/hide header effect when scrolling. An error message "Uncaught TypeError: header is null" appears in the console while scrolling on the page. Even after placing the js script src at the end of the body, the same error persists. Th ...

Determine the number of working days prior to a specified date in a business setting

How can I calculate X business days before a given date in JavaScript when I have an array of holidays to consider? I am currently thinking about using a while loop to iterate through the dates and checking if it is a business day by comparing it with the ...

Issues with JavaScript switch statement not functioning as expected

JavaScript: let Page = parseInt($(".active_pagination").data("number")); let First = parseInt($(".pagination_number:first").data("number")); let Last = parseInt($(".pagination_number:last").data("number")); alert("Page: "+Page+" First: "+First+" L ...