0

I am using cookie authentication in ASP.NET Core Web API. When I am requesting for login from Postman, cookie is shown in Postman.

But when I am requesting it from ajax, the cookie does not get stored in the browser.

Here is my Ajax request - am I missing anything in Ajax?

$.ajax({

    url: 'http://localhost:61610/api/auth/login',
    method: 'POST',
    xhrFields: {
        'Access-Control-Allow-Credentials': true
    },
    data: JSON.stringify(para),
    dataType: 'application/json',
    contentType: 'application/json; charset=utf-8',
    success: function (result, status, jqXHR) {
        console.log(result);
        alert(status);
    },
    error: function (jqXHR, textStatus, errorThrown) {
        alert(textStatus);
    }
});
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425

2 Answers2

1

you should try this

 xhrFields: {
      withCredentials: true
   }
Serge
  • 28,094
  • 4
  • 11
  • 35
-1

You need do some change in your ajax:

         $.ajax({
                url: 'http://localhost:61610/api/auth/login',
                method: 'POST',
                xhrFields: {              
                    withCredentials: true                 
                },
                data: JSON.stringify(a),
                dataType: 'application/json',
                contentType: 'application/json; charset=utf-8',
                success: function (result, status, jqXHR) {
                    console.log(result);
                    alert(status);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    alert(textStatus);
                }
            });

then you can send ajax with cookie enter image description here

Here is a link with a more detailed explanation :https://stackoverflow.com/questions/27406994/http-requests-withcredentials-what-is-this-and-why-using-it

Xinran Shen
  • 2,336
  • 2
  • 2
  • 6