I’m trying to access data from sync gateway REST API (get document) from an Angular web app authenticating with the SyncGatewaySession, but I’m unable to get it working.
The following cURL statement is working:
curl -X GET 'https://myserver.cloud:4984/bucket/docID' -H 'Accept: application/json' -H 'Cookie: SyncGatewaySession=d29cf8e88a005df9bf9ae1438ff50c0173310a15'
but when I try to replicate the same call in browser JS, the browser omits to add the cookie header because is not specified by Access-Control-Allow-Headers header in OPTIONS of sync gateway API. The OPTIONS specifies the following values;
**Access-Control-Allow-Headers**: Content-Type, SyncGatewaySession, Authorization, Access-Control-Allow-Headers, withCredential, Access-Control-Allow-Credentials
so I’ve tried to add the header called SyncGatewaySession, like this:
the header is now sent by the browser but I got 401 - Unauthorized response (same sending header with cURL)
Even adding “Cookie” to CORS Access-Control-Allow-Headers section of sync gateway config didn’t help.
The use of the name “Cookie” is forbidden as per XHR specification.
I’ve been able to set it with a simple
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.crossDomain = true;
and get a valid response from Sync Gateway, but it seems there is no way to add it in the Angular 2 client, because browser explicitly refuses to add it and gives console error:
Refused to set unsafe header "Cookie"
I can’t save cookie in browser because my backend and frontend are hosted in different subdomains.
Isn’t there another way to use session credential to access Sync Gateway REST API?
Glad to hear that you are able to get response back from Sync Gateway by using XMLHttpRequest. Then it seems something specific with Angular2? I know nothing about Angular, but happen to see this discussion: https://stackoverflow.com/questions/35602866/how-to-send-cookie-in-request-header-for-all-the-requests-in-angular2 Hope it can help you.
Yes, more than Angular2 specific is “browser” specific. You can’t set Cookie header so you have to deal with browsers security limitations while working with cookies. To finally solve this issue I had to setup a reverse proxy to have both web app and sync gateway in the same domain.
There’s no need to insist on the cookie being sent as a header.
You can just use:
document.cookie='SyncGatewaySession=your-session-id' before connecting to SG
Alternatively you could also just fire an ajax call to your app server (which you probably already do to generate the session id for the user) and have it set the cookie for you.
No need for a reverse proxy .
Here’s a little write up on this scenario