Skip to content

Instantly share code, notes, and snippets.

@javan
Created November 30, 2013 22:06
Show Gist options
  • Star 37 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save javan/7725255 to your computer and use it in GitHub Desktop.
Save javan/7725255 to your computer and use it in GitHub Desktop.
Prevent cross-origin js requests
class ApplicationController < ActionController::Base
before_filter :ensure_xhr
private
def ensure_xhr
if request.get? && request.format && (request.format.js? || request.format.json?)
head :forbidden unless request.xhr?
end
end
end
@javan
Copy link
Author

javan commented Dec 1, 2013

Don't bork your JSON API:

class Api::BaseController < ApplicationController
  skip_before_filter :ensure_xhr
end

@tundal45
Copy link

tundal45 commented Dec 2, 2013

@javan Confused why you would need to skip the before filter in API. Wouldn't request.xhr? be true?

@Draiken
Copy link

Draiken commented Dec 2, 2013

@tundal45 Not really. I can access an API through any place, not just the browser.

@javan
Copy link
Author

javan commented Dec 2, 2013

@tundal45 request.xhr? is only true for most ajax requests. If your API is for consumption over HTTP, you'll need to skip that check.

@dhh
Copy link

dhh commented Dec 2, 2013

Worth noting is that this would go hand-in-hand with all GET .js requests getting the xhr header added. So this would protect on all verbs, including GET.

@homakov
Copy link

homakov commented Dec 2, 2013

API doesn't usually use cookies so no private info can be CSRF-ed.

@homakov
Copy link

homakov commented Dec 2, 2013

@javan what about actions working like this

def index
  render 'index.js.erb'
end

They don't have specified params[:format]. I've seen it in the wild

@javan
Copy link
Author

javan commented Dec 2, 2013

@homakov If the incoming request doesn't have .js in the path or a javascript Accept header, request.format.js? will be false. If you've made the decision to still return js in that scenario then the above solution will not protect you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment