sinatra-authentication
sinatra-authentication copied to clipboard
XSRF / CSRF
There seems to be little or no protection for XSRF / CSRF.
Simple solution:
before do
if request.post?
if session[:csrf] != params[:csrf]
halt 503
end
end
time = Time.now.to_s
@key = Digest::SHA1.hexdigest(time)
session[:csrf] = @key
end
Then on all form views add:
<input type="hidden" name="csrf" value="<%= @key %>" />
I should have some spare time next weekend. I'll take a look at this if @maxjustus doesn't nail it first.
My "simple solution" can be added to any Sinatra app. I think if we're looking to alter the original, a better solution may be available.
A better solution is to use rack/csrf
require 'rack/csrf'
use Rack::Csrf, :raise => true
Then in the views
<%= Rack::Csrf.csrf_tag(env) %>