PouchDB authentication triggering CORS preflight request
Asked Answered
A

2

8

The following code (using the PouchDB Authentication plugin) fails because it triggers the browser to send a CORS preflight request, and CouchDB does not support the OPTIONS HTTP method.

var db = new PouchDB("http://localhost:5984/mydb");
db.login('username', 'password');
// assume the database URL and login info are valid

Here is the error (in Chrome). Note that this issue also occurs in Edge, but not in Firefox:

XMLHttpRequest cannot load http://localhost:5984/_session. Response for preflight has invalid HTTP status code 405

And here are the headers that Chrome is sending for the request (they are not significantly different in Firefox):

POST /_session HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 25
Accept: application/json
Origin: http://localhost:8080
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Referer: http://localhost:8080/
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8,es-419;q=0.6,es;q=0.4

I have already enabled CORS via the add-cors-to-couchdb Node script. Things I have tried:

  • Manually adding OPTIONS as a method under [cors] in my local.ini
  • Passing { ajax: { content_type: "text/plain" } } as the third argument to login

So, my question is:

  • How can I prevent the preflight request from being triggered? Looking at the MDN documentation, it doesn't seem necessary.
  • If the previous is not possible, how can I set my CouchDB server up to respond to preflight requests?
Abyssinia answered 9/8, 2016 at 20:32 Comment(0)
R
3

Hitting this same issue. Seems Chrome has recently started being a little more aggressive about sending the OPTIONS preflight. A partial work around was to specify a specific origin in the CORS header instead of '*', so

curl -X PUT $HOST/_config/cors/origins -d '"localhost:8080"'

or similar.

I still am getting the preflight error, but now PouchDB successfully authenticates, so I can just ignore the error. I think the fix is to get CouchDB to respond to OPTIONS on the _session url.

Edit, more info here https://github.com/nolanlawson/pouchdb-authentication/issues/111

Robenarobenia answered 9/8, 2016 at 23:19 Comment(1)
Thanks for the suggestion. Unfortunately, when I tried specifying the origin as you describe, the result was the same as before (same error, no authentication). Also thanks for the link, the information is very helpful!Abyssinia
D
0

With the latest PouchDB you authenticate like so:

var remote = new PouchDB("http://user:password@localhost:4984/bucket/");
Durrett answered 27/7, 2020 at 8:5 Comment(2)
Never authenticate like this - the credentials are in plain site.Paternal
There are a lot of ways to hide this.Durrett

© 2022 - 2024 — McMap. All rights reserved.