Sanitize Backbone.js Models to prevent XSS

This isn’t groundbreaking code, but you may find it useful to know how to take a step to prevent XSS attacks when implementing Backbone MV*. Some JavaScript frameworks automatically escape or sanitize the values being passed to the model. Backbone does not. However, the library it’s built on (Underscore.js) does provide an easy way to escape values.

First, in your Model, create your initialize() method, and in it, use the _.each method to iterate over the attributes object, passing the value to a method belonging to the Model named “sanitize”.

var CartItem = Backbone.Model.extend({
  initialize: function() {
    _.each(this.attributes, function (val, key)
      this.set(key, this.sanitize(val));
    }, this);
  }
});

Let’s add our sanitize() method. In this method, simply take in the string as a parameter, and return the escaped version of it, using Underscore’s _.escape method.

var CartItem = Backbone.Model.extend({
  initialize: function() {
    _.each(this.attributes, function (val, key) {
      this.set(key, this.sanitize(val));
    }, this);
  },
  sanitize: function (str) { 
    return _.escape(str) 
  } 

});

I recommend sanitizing in your model’s initializer so that you ensure it’s properly scrubbed before calling Model.save() and sending nasty XSS or SQL injection to your server. Also, sanitize anywhere you update the model or allow edits to the model.

I hope you found this post useful. If you have anything to add or find any problems, let me know.

Advertisements

4 thoughts on “Sanitize Backbone.js Models to prevent XSS

  1. The initialize() method is only used when you call new CartItem(jsonModel); but will not be called if you do something like cartItem.fetch() (where the parse() method will be used). So you should sanitize in the setter method and parse method as well to be safe. An alternative way would be to always use the escape method right in your templates like

    for underscore templates or only {{somAttribute}} instead of {{{ in handlebars.

    Additionally to sanitize before model.save() is not a good idea, because the client can modify the code and send it to your backend API anyway. So for SQL injections you have to prevent them on the server.

    • This was written way prior to the current release of backbone. It hasn’t been updated in a while. Thanks for your contribution though!

      Another approach would have been to just escape using vanilla js in the templates, for sure.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s