Azizur Rahman
Azizur Rahman

Reputation: 68

Why cookie does not store in browser in ASP.NET Core Web API?

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);
    }
});

Upvotes: 0

Views: 278

Answers (2)

Xinran Shen
Xinran Shen

Reputation: 9993

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?

Upvotes: 0

Serge
Serge

Reputation: 43959

you should try this

 xhrFields: {
      withCredentials: true
   }

Upvotes: 1

Related Questions