Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Rough, simple Rack::Csrf extension for Sinatra
require 'sinatra'
require 'csrf'
use Rack::Session::Cookie
apply_csrf_protection
# Here follow the route handlers.
require 'sinatra/base'
require 'rack/csrf'
module Sinatra
module Csrf
module Helpers
# Insert an hidden tag with the anti-CSRF token into your forms.
def csrf_tag
Rack::Csrf.csrf_tag(env)
end
# Return the anti-CSRF token
def csrf_token
Rack::Csrf.csrf_token(env)
end
# Return the field name which will be looked for in the requests.
def csrf_field
Rack::Csrf.csrf_field
end
end
# Turn on the anti-CSRF check. See Rack::Csrf documentation for the
# available options.
def apply_csrf_protection(options = {})
opts = {:raise => true}.merge(options)
use Rack::Csrf, opts
helpers Csrf::Helpers
end
end
register Csrf
end
require 'sinatra/base'
require 'csrf'
class ModularApp < Sinatra::Base
register Sinatra::Csrf
use Rack::Session::Cookie
apply_csrf_protection
# Here follow the route handlers.
end
@ddebernardy

This comment has been minimized.

Copy link

ddebernardy commented Jun 21, 2011

Not sure I'm getting this. Should one use this, or the Sinatra contrib?

@baldowl

This comment has been minimized.

Copy link
Owner Author

baldowl commented Jun 21, 2011

As I wrote in the blog post (http://baldowl.github.com/2011/05/06/rough-simple-rack-csrf-extension-for-sinatra.html), if you use sinatra-contrib don't use Rack::Csrf; if you choose to use Rack::Csrf, then you could use it with Sinatra with or without this totally untested extension.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.