Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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