Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails InvalidCrossOriginRequest

I have a remote: true link on a page in my Rails app which calls a .js version of the same page and then runs a script to update the pages content in place.

It was working fine but since yesterday I now get 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. everytime I click one of those links.

Any ideas on how I can stop this?

like image 663
rctneil Avatar asked Mar 27 '15 21:03

rctneil


1 Answers

Add this to the controller that is rendering your page fragment

class FooController < ApplicationController
    protect_from_forgery except: :index

Where index is the name of the action you wanna skip this protection


Cross-Origin Policy

The error you were getting is because of what is called Cross-Origin policy. It's a standard present in every browser that don't allow a page to run scripts from other domains. The way to go around this is adding a header to the http request allowing your content to be run in other domains.

Wikipedia has an explanation for this:

The second technique for relaxing the same-origin policy is standardized under the name Cross-Origin Resource Sharing. This standard extends HTTP with a new Origin request header and a new Access-Control-Allow-Origin response header. It allows servers to use a header to explicitly list origins that may request a file or to use a wildcard and allow a file to be requested by any site. Browsers such as Firefox 3.5, Safari 4 and Internet Explorer 10 use this header to allow the cross-origin HTTP requests with XMLHttpRequest that would otherwise have been forbidden by the same-origin policy.

http://en.wikipedia.org/wiki/Same-origin_policy

like image 106
João Paulo Motta Avatar answered Oct 23 '22 09:10

João Paulo Motta