Skip to content

Protecting from cross site request forgery

kr1zmo edited this page Feb 11, 2013 · 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 the 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 The token is stored in the sameOriginToken property. When protectFromForgery is called in the application controller, the token is accessible in all controllers. If it is only specified on a certain controller, it is only accessible inside that controller.

Controller method example:

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

Template example:

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

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

Supplying the Token

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 supply the token with a form.

For example:

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

JSON:

You can supply the token with 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]"}

Json key/value pairs supplied will populate the params object.