Skip to content

Instantly share code, notes, and snippets.

@baldowl
Created May 6, 2011 06:49
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save baldowl/958530 to your computer and use it in GitHub Desktop.
Save baldowl/958530 to your computer and use it in GitHub Desktop.
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
Copy link

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

@baldowl
Copy link
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