Created
May 6, 2011 06:49
-
-
Save baldowl/958530 to your computer and use it in GitHub Desktop.
Rough, simple Rack::Csrf extension for Sinatra
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'sinatra' | |
require 'csrf' | |
use Rack::Session::Cookie | |
apply_csrf_protection | |
# Here follow the route handlers. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
Not sure I'm getting this. Should one use this, or the Sinatra contrib?