Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save kissu/9d061acefbe04302aaa936f8f8cbc036 to your computer and use it in GitHub Desktop.
Save kissu/9d061acefbe04302aaa936f8f8cbc036 to your computer and use it in GitHub Desktop.
Fixes unauthorized cross-origin response problem for .js templates (problem description in Russian http://habrahabr.ru/post/209618/) in Ruby On Rails 3.2. For Rails 4 just save https://raw2.github.com/rails/rails/4f4fdd643f9d19fbbeeec3ac77674f791c9beffa/actionpack/lib/action_controller/metal/request_forgery_protection.rb to config/initializers/u…
# config/initializers/unauthorized_cross-origin_response_fix.rb
#
# Fixes unauthorized cross-origin response problem for .js templates (problem description in Russian http://habrahabr.ru/post/209618/)
# in Ruby On Rails 3.2, idea and code extracted from https://github.com/rails/rails/blob/4f4fdd643f9d19fbbeeec3ac77674f791c9beffa/actionpack/lib/action_controller/metal/request_forgery_protection.rb
#
# for Rails 4 just save https://raw2.github.com/rails/rails/4f4fdd643f9d19fbbeeec3ac77674f791c9beffa/actionpack/lib/action_controller/metal/request_forgery_protection.rb
# to config/initializers/unauthorized_cross-origin_response_fix.rb
#
# for Rails 4.1 there is https://github.com/rails/rails/pull/13345)
module ActionController
class InvalidCrossOriginRequest < ActionControllerError; end
module RequestForgeryProtection
module ClassMethods
def protect_from_forgery(options = {})
self.request_forgery_protection_token ||= :authenticity_token
prepend_before_filter :verify_authenticity_token, options
append_after_filter :verify_same_origin_request # added this line to original method
end
end
protected
CROSS_ORIGIN_JAVASCRIPT_WARNING = "Security warning: an embedded " \
"<script> tag on another site requested protected JavaScript. " \
"If you know what you're doing, go ahead and disable forgery " \
"protection on this action to permit cross-origin JavaScript embedding."
private_constant :CROSS_ORIGIN_JAVASCRIPT_WARNING
def verify_same_origin_request
if request.get? && content_type =~ %r(\Atext/javascript) && !request.xhr?
logger.warn CROSS_ORIGIN_JAVASCRIPT_WARNING if logger
raise ActionController::InvalidCrossOriginRequest, CROSS_ORIGIN_JAVASCRIPT_WARNING
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment