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
  • 732,580
  • 175
  • 1,330
  • 1,459

2 Answers2

1

you should try this

 xhrFields: {
      withCredentials: true
   }
Serge
  • 40,935
  • 4
  • 18
  • 45
0

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:

Http requests withCredentials what is this and why using it?

Tieson T.
  • 20,774
  • 6
  • 77
  • 92
Xinran Shen
  • 8,416
  • 2
  • 3
  • 12