Search code examples
web-servicesbackbone.jsbasic-authentication

How do I authenticate and consume an external api with backbone?


I'm trying to create a very basic little backbone app that displays stats from my company's Harvest account. They have a REST API which authenticates via Basic Auth or oAuth. I seem to be faced with two problems here:

  • Authentication
  • Cross-origin requests

So I've started with setting the url for my collection to the respective url:

var Projects = Backbone.Collection.extend({
    url: 'https://mycompany.harvestapp.com/projects',
});

And I've tried using this basic auth plugin but I can't tell if that part is working because I'm still getting Access-Control-Allow-Origin errors.

What's the best way to go about this?


Solution

  • This other StackOverflow question is similar and has more details that you should take a look at.

    But the general idea is this, if you don't have access to the remote server (which I presume you do not with Harvest) then you need to perform the cross-site requests from your own server that you do control, most likely the one you are deploying this backbone app on. That means writing some server-side code (PHP, Node, etc.) to perform the requests (perfectly legal from server side) and then having your client (Backbone app) request from these scripts.

    Here is a brief/pseudo-example with php:

    request.php

    <?php
        echo file_get_contents('https://mycompany.harvestapp.com/projects');
    ?> 
    

    projects.js

    var Projects = Backbone.Collection.extend({
        url: 'request.php',
    });