TMichel
TMichel

Reputation: 4462

Basic authentication with CouchDB

I am trying to figure out how to use basic authentication (i.e. http://test:test@localhost:5984/mydb) in CouchDB 1.3.1.

In the Futon:

Then i just test connection.

Using curl:

curl GET http://localhost:5984/mydb

returns 401 unauthorized, that's good.

curl GET http://test:test@localhost:5984/mydb

returns 200, so everything works as expected using curl.

Using browser or $.ajax:

Both return 401 on the url http://test:test@localhost:5984/mydb.

So, questions:

Upvotes: 5

Views: 10202

Answers (2)

Carlos Fernando
Carlos Fernando

Reputation: 76

You forgot to put the authentication information in the header. Try it!

 $(document).ready(function () {
     $.ajax({
      url: 'http://127.0.0.1:5984/mydb', //Your api url
      type: 'GET', //type is any HTTP method
      xhrFields: {
        withCredentials: true
      },
       headers: {
                'Authorization': 'Basic ' + btoa('MyUser:MyPassWord')
            },
            success: function (response) {
                var resposta = response            
            },
            error: function (err) {
                var t = err.responseText;
                console.log("Erro de requisição: " + err.responseText);
            }
        });
    });

Source: https://zinoui.com/blog/ajax-basic-authentication

Upvotes: 2

fet
fet

Reputation: 624

It's called Cross Origin Resource Sharing. Basically, there's a limitation placed on the ajax calls a browser can make. It's a security feature that doesn't allow the browser to load resources from anywhere arbitrarily.

It seems like you would want to be able to do that, after all a click loads an arbitrary resource. But if any old javascript program could load any other resources there are a lot of ways that it could be hijacked to inject code or steal information.

CURL gets around that by not being limited by CORS. It just makes any old request you'd like.

Additionally, you can start a session by querying localhost:5984/_session, at which point all of your following queries will be sent with a security token cookie. jQuery.couch is a nice basic resource for some common functions.

Upvotes: 5

Related Questions