Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My PHP api requires a user token be submitted with every request from my front-end Backbone app to make sure the user...

  1. Is active
  2. Has permissions to access the resource

What is the easiest way to set this up in Backbone? I am guessing the only way is to overwrite Backbone.sync, but what would the code look like? CoffeeScript preferred.

EDIT

Two more things
1. I would like to redirect the user to /login if I get a 403: Access Forbidden Error
2. I pull the user model which includes the token from localStorage when the app is bootstrapped
3. I have a baseModel and baseCollection which all models / collections come from

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
333 views
Welcome To Ask or Share your Answers For Others

1 Answer

Backbone uses jQuery's $.ajax, so you can use $.ajaxSetup to "set default values for future Ajax requests":

$.ajaxSetup({
   headers: {
     "accept": "application/json",
     "token": YOUR_TOKEN
   }
});

Update: an improvement to this idea (thanks to @Glen) is to use $.ajaxSend to check for the existence of a token each time before setting it in the headers of the request:

$(document).ajaxSend(function(event, request) {
   var token = App.getAuthToken();
   if (token) {
      request.setRequestHeader("token", token);
   }
});

Where App.getAuthToken() is a function in your Backbone app.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...