To get facebook to accept localhost, use http://127.0.0.1:3000
.
To stifle the CSRF error (allow CSRF) in a particular controller,
skip_before_action :verify_authenticity_token!
This should solve 90% of your problems.
Question
I've done a fair amount of research on my problem to no avail hence why I turn to the great people at stackoverflow :)
Alright, I followed Ryan Bates' tutorial on Facebook login but it seems like Facebook has changed quite a bit in the two years since the tutorial was made. I've struggled to get Facebook to accept localhost:3000/ as an App Domain. What I ended up doing is setting the Website URL and App Domain to my staging Heroku app and in Advanced/Valid OAuth redirect URIs I put in localhost:3000/
Ok here's the problem. When I go to localhost:3000/auth/facebook, I get the following error:
OmniAuth::Strategies::OAuth2::CallbackError at /auth/facebook/callback
csrf_detected | CSRF detected
OmniAuth::FailureEndpoint#raise_out!
omniauth (1.2.1) lib/omniauth/failure_endpoint.rb, line 25
However, when I go back to my website, I'm actually logged in. Weird. I should also add that I'm using my developer account to login. Anyway here's my code:
sessions_controller.rb
def facebook_login
if request.env['omniauth.auth']
user = User.from_omniauth(env['omniauth.auth'])
session[:user_id] = user.id
redirect_back_or root_path
end
end
user.rb
class User < ActiveRecord::Base
include Tokenable
has_many :events
has_secure_password
validates_presence_of :email, :first_name, :last_name
validates_uniqueness_of :email, format: /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates_length_of :password, minimum: 6, unless: Proc.new { |a| !a.oauth_token.nil? }
def to_param
token
end
def self.from_omniauth(auth)
where(auth.slice(:provider, :uid)).first_or_create do |user|
user.provider = auth.provider
user.uid = auth.uid
user.first_name = auth.info.first_name
user.last_name = auth.info.last_name
user.email = auth.info.email
user.password = auth.credentials.token
user.password_confirmation = auth.credentials.token
user.oauth_token = auth.credentials.token
user.oauth_expires_at = Time.at(auth.credentials.expires_at)
end
end
end
routes.rb
get 'auth/:provider/callback', to: 'sessions#facebook_login'
get 'auth/failure', to: redirect('/')
omniauth.rb
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
end
Any help is much appreciated. Thanks!
Solution
To get facebook to accept localhost, use http://127.0.0.1:3000
.
To stifle the CSRF error (allow CSRF) in a particular controller,
skip_before_action :verify_authenticity_token!
This should solve 90% of your problems.