Search code examples
ruby-on-railsfacebookauthenticationfacebook-oauth

Fix Rails oauth facebook x-frame-options sameorigin error


I can't for the life of me get my Facebook canvas app to display. Chrome console displays this error and nothing shows up inside the iframe - it's blank:

Refused to display 'http://mysite.dev/' in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'.

I'm using Rails 4.0.0.rc1 and omniauth-facebook 1.4.1, following the Railscast on Facebook Authentication as a guide. I didn't use any of the Javascript code since it was optional and ideally the app should only be accessed within Facebook.

routes.rb

  match 'auth/:provider/callback', to: 'sessions#create', via: [:get, :post]
  match 'auth/failure', to: redirect('/'), via: [:get, :post]
  match 'signout', to: 'sessions#destroy', as: 'signout', via: [:get, :post]

sessions_controller.rb

class SessionsController < ApplicationController

  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url
  end

  def destroy
    session[:user_id] = nil
    redirect_to root_url
  end

application_controller.rb

I had to comment this out because I kept getting InvalidAuthenticityToken errors which cost me the other half of my day. A bit more on that here.

  # protect_from_forgery with: :exception

Facebook settings

  • App domain: myapp.dev
  • Canvas URL: http://myapp.dev
  • Secure Canvas URL: -- blank -- if https is specified, I get webpage is unavailable

Please help before I start flipping desks. :)


Solution

  • In Rails 4, X-FRAME-OPTIONS is set to SAMEORIGIN in the headers, which I guess prevents it from being loaded in a frame, as described in this issue. One person notes the difficulty this will cause Facebook app developers.

    I managed to solve this by adding the following to application.rb:

    config.action_dispatch.default_headers[:'X-Frame-Options'] = "ALLOW-FROM https://apps.facebook.com"
    

    I also used Forward to create a domain to allow Facebook to access my local development machine. I entered this domain in the canvas and secure canvas fields in Facebook. Highly recommended.

    Further info here: