sinatra-authentication icon indicating copy to clipboard operation
sinatra-authentication copied to clipboard

XSRF / CSRF

Open timmillwood opened this issue 12 years ago • 4 comments

There seems to be little or no protection for XSRF / CSRF.

timmillwood avatar Oct 17 '12 11:10 timmillwood

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 %>" />

timmillwood avatar Oct 17 '12 12:10 timmillwood

I should have some spare time next weekend. I'll take a look at this if @maxjustus doesn't nail it first.

cmhobbs avatar Oct 22 '12 05:10 cmhobbs

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.

timmillwood avatar Oct 22 '12 08:10 timmillwood

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) %>

timmillwood avatar Oct 29 '12 14:10 timmillwood