Skip to content

Protecting from cross site request forgery

kr1zmo edited this page Sep 17, 2012 · 35 revisions

Geddy provides basic, built-in protection from cross-site request forgery. This ensures that requests with destructive methods (e.g., PUT, POST, DELETE) are only made from pages served from your server.

Enable CSRF

Simply call the protectFromForgery method on the desired controllers. (To add this protection for all controllers, call it in the Application controller.)

For example:

var Application = function () {
  this.protectFromForgery();
};

exports.Application = Application;

##Rendering the Token When enabled, the token is always supplied in the sameOriginToken property.

Controller example:

this.add = function (req, resp, params) {
  this.respond({token: this.sameOriginToken});
};

Template example:

<input name="same_origin_token" type="hidden" value="<%= token %>"/>

Supplying the Token

Once protectFromForgery is enabled, requests with destructive methods will be rejected by the server unless they include a 'same_origin_token' parameter, with the value from the sameOriginToken property on the current controller-instance.

Form

You can send the token via a form.

For example:

<input name="same_origin_token" type="hidden" value="[same-origin-token]"/>

JSON

You can send the token via json.

Supply the json content-type header Content-Type: application/json. Then, supply json as raw body in the request:

{"same_origin_token" : "[same-origin-token]"}

The json key/value pairs supplied will populate the params object.

The token value depends on your application-secret. Generate one by running geddy secret inside your app.