Question

I am new to backbone.js. I built a rest api with php and I want to connect to it with backbone.js. I am having a tough time with passing the http basic auth that my rest api uses for authentication.

I can access my rest api easily by using curl from the command line like this

curl -u username:password -X GET http://api.mysite.com/user

But when I try to do a fetch (which is pretty much all I am trying to do) I get a response from my rest api that the authentication failed.

Here is my call from backbone.js

user.fetch({headers:{'Authorization':'Basic username:password'}});

With backbone.js I am getting back the response I would expect when the basic auth fails. My question is, since I know my rest api with authenticate with curl, why won't it authenticate with the above javascript?

Also, when I look at the headers sent in the js console I don't see anything about Authorization.

UPDATE

I tried the plugin listed in the comment below but got the same result

Here is my code

var User=Backbone.Model.extend({
    url: 'http://api.mysite.com/user'
}); 
var user=new User();

user.credentials = {
    username: 'username',
    password: 'password'
};

user.fetch();
Was it helpful?

Solution 2

I added "Authorization" to the allowed headers list and that did the trick.

header("Access-Control-Allow-Headers: Authorization, Origin, X-Requested-With, Content-Type, Accept");

OTHER TIPS

The username and password need to be encoded with Baes64 before being sent.

One easy way to do this (at least for testing) is to configure all jQuery ajax requests to send the info (Backbone uses jQuery for the ajax calls):

$.ajaxSetup(
  beforeSend: function(xhr){
    xhr.setRequestHeader("Authorization", "Basic " + btoa("USERNAME" + ":" + "PASSWORD"));
  }
);

Note that btoa is the function that will encode the params with Base64. Now you can call user.fetch() and it should work properly: you don't need to provide the credentials, because we've configured jQuery to send them for us (all the time).

Of course, depending on your situation (e.g. using multiple APIs), you might prefer to specify the beforeSend attribute within each request, or have it defined within a Backbone syncfunction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top