Swastik Pareek
Swastik Pareek

Reputation: 161

CORS - Server side cookie is not getting saved on chrome browser

There is a node server which on accepting correct credentials of a user, passport js creates and sends a session cookie in request header by name of set-cookie.

But when I do an ajax request from my chrome browser accepts the request it doesn't adds the cookie on the client side . so when a new request generates from client side , the server doesn't authenticates it and throws 401.

I am confused whether it is a browser issue or an I am missing something from AJAX request

Please help.

Upvotes: 5

Views: 6670

Answers (4)

NormVent
NormVent

Reputation: 249

I was experiencing this issue using Angular 4 in Chrome (IE was working).

Requests from client on localhost:4200 to WebApi on localhost:24336. Had all the CORS setup, "Access-Control-Allow-Credentials" value="true" "Access-Control-Allow-Origin" value="http://localhost:4200", etc. and was passing { withCredentials: true } in every request, i.e. like http.post(url, {}, { withCredentials: true }) .

The fix, for me, was to set the default RequestOptions to {withCredentials: true } by following the steps https://angular.io/api/http/BaseRequestOptions and adding the following to providers: in app.module.ts

,{provide: RequestOptions, useClass: MyOptions}

Upvotes: 2

Swastik Pareek
Swastik Pareek

Reputation: 161

Thanks for your answers . I was trying it withCredentials thing , but the session cookie was not getting set on my local.

The reason I figured out was the allowed origins. I need to set the allowed origins at the backend.

The XHR by is a secure request if passed with credentials property. So the client side browser only save the cookie if the allowed origin matches request origin.

So the simple fix was to change the host to something which matches to allowed origin .

At node end I need to do origin: 'domain.com' and at the front end I need to set my server (localhost) to point to test.domain.com. and bingo . It worked.!

Upvotes: 2

Vladimir Hovsepyan
Vladimir Hovsepyan

Reputation: 11

If you are using XHR request then you need set withCredentials to true. It should fix problem if no please provide code

Upvotes: 1

prateekbh
prateekbh

Reputation: 303

If you are using 'fetch', you need to add a key

{
        headers: req.headers,
        credentials: 'include'
}

Upvotes: 3

Related Questions