13

I integrated omniauth-facebook using https://github.com/plataformatec/devise/wiki/OmniAuth%3a-Overview. But I am getting error of :

Could not authenticate you from Facebook because "Invalid credentials".

And in logs, getting this:

Authentication failure! invalid_credentials: OAuth2::Error, : {"error":{"message":"This authorization code has been used.","type":"OAuthException","code":100}}

I have devise installed. When i click on facebook sign in link, it comes back to devise sign "www.mealnut.com/user/sign_in#=" and gives above error. I checked the solution for "Invalid credentials" on https://github.com/plataformatec/devise/wiki/OmniAuth%3a-Overview and as mentioned there, my app is header set for App Type = Web. Not getting why it is not working.

Also my app is pending review from facebook. But i don't think it is related to this error. Following are the things i did for omniauth-facebook:

Gemfile contains:

gem "omniauth", "~> 1.1.4"
gem 'omniauth-facebook', '1.4.1'

In user model, added:

devise :omniauthable, :omniauth_providers => [:facebook]
attr_accessible :provider, :uid

  def self.find_for_facebook_oauth(auth, signed_in_resource=nil)
    user = User.where(:provider => auth.provider, :uid => auth.uid).first
    unless user
    user = User.create(name:auth.extra.raw_info.name,
                       provider:auth.provider,
                       uid:auth.uid,
                       email:auth.info.email,
                       password:Devise.friendly_token[0,20]
                      )
  end
user
end

devise.rb

require "omniauth-facebook"
config.omniauth :facebook, "APP_ID", "APP_SECRET", :scope => "offline_access, email" 

omniauth.rb:

OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
 provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], {:provider_ignores_state => true}
end

route.rb:

devise_for :user, :controllers => { :omniauth_callbacks => "omniauth_callbacks" }

Omniauth controller:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController
  def facebook
    @user = User.find_for_facebook_oauth(request.env["omniauth.auth"], current_user)

    if @user.persisted?
      sign_in_and_redirect @user, :event => :authentication #this will throw if @user is not activated
      set_flash_message(:notice, :success, :kind => "Facebook") if is_navigational_format?
    else
      session["devise.facebook_data"] = request.env["omniauth.auth"]
      redirect_to new_user_registration_url
    end
  end
end

Can anybody help in this?

Gaurav Sharma
  • 477
  • 9
  • 24
user2206724
  • 1,265
  • 3
  • 20
  • 38
  • Im having the same problem, however my client_id (the api key/id) is being passed, can you check your console output (if chrome ,network tab and check facebook, path is users/auth) you should see in the headers something like this Location:https://graph.facebook.com/oauth/authorize?response_type=code&client_id=************&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fusers%2Fauth%2Ffacebook%2Fcallback&scope=email I have purposely removed the key – Richlewis Apr 24 '13 at 12:38
  • in your case though it could be as simple as changing omniauth-facebook to version 1.4.0 – Richlewis Apr 24 '13 at 12:39
  • When i am not logged in to facebook, it gives following in header: https://www.facebook.com/login.php?api_key=*********&skip_api_login=1&display=page&cancel_url=http%3A%2F%2Fwww.mealnut.com%2Fuser%2Fauth%2Ffacebook%2Fcallback%3Ferror_reason%3Duser_denied%26error%3Daccess_denied%26error_description%3DThe%2Buser%2Bdenied%2Byour%2Brequest.%26state%376&fbconnect=1&next=https%3A%2F 2Fwww.facebook.com%2Fdialog%2Fpermissions.request%3F_path%3Dpermissions.request%26app_id continued... – user2206724 Apr 24 '13 at 14:12
  • tried for version 1.4.0 but no help! some people got it working for 1.4.1 – user2206724 Apr 24 '13 at 14:18
  • 1
    looks like you have keys being declared twice? ie you still have an omniauth.rb file, you dont need this as they should be in your devise.rb file – Richlewis Apr 24 '13 at 14:21
  • i tried removing it from omniauth. But it gives error that couldnt find clicd id. Then i tried removing from devise. but same issue. – user2206724 Apr 24 '13 at 15:38
  • thats to be expected, ensure you are using version 1.4.0 as i previously said and dont use ENV variables when setting the keys..Also in the facebook application ensure your app is set to web, let me know how this goes as i got mine working, it also looks like your missing a method in your model, just follow the docs in devise and it works – Richlewis Apr 24 '13 at 18:48
  • I have included the method given in docs. I mentioned it in question too. Tried 1.4.0 but no help. I didnt get this: "dont use ENV variables when setting the keys." I have not used it as written above the omniauth.rb – user2206724 Apr 24 '13 at 19:28
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/28841/discussion-between-richlewis-and-user2206724) – Richlewis Apr 24 '13 at 19:33
  • dont forget to add the answer, help other people – Richlewis Apr 25 '13 at 06:52
  • yes. Will add it once done with necessary changes :-) – user2206724 Apr 25 '13 at 08:04
  • hey @Richlewis, added my answer :-) – user2206724 Apr 25 '13 at 20:03
  • Does anyone still having issues with: * omniauth-facebook (4.0.0) * omniauth-oauth2 (1.4.0) – robzdc Aug 18 '16 at 21:11

6 Answers6

39

Thought I'd chip in here since this came up for me when trying to search for a solution for Could not authenticate you from Facebook because “Invalid credentials”

The problem is with Facebook API version >=2.3 you need to set {token_params: {parse: :json}} to your provider config.

devise.rb

config.omniauth :facebook,
    APP_ID,
    APP_SECRET,
    token_params: { parse: :json } # <----- this line is NB

Answer found on this issue for omniauth-oauth2

UPDATE Aug 2018: The "invalid credentials" issue reoccurred, I had to remove the token_params setting for it to work again - so this may not be an issue anymore

Stan Bondi
  • 4,118
  • 3
  • 24
  • 35
6

Got it working!

My routes.rb and user.rb were wrong. And changed omniauth.rb too! Here are the previous and after files:

My routes.rb was:

devise_for :user, controllers: { registration: "registration" }
devise_for :user, controllers: { omniauth_callbacks: "omniauth_callbacks" }

So it was calling devise twice. I changed it to:

devise_for :user, controller: { registration: "registration", omniauth_callbacks: "omniauth_callbacks" }

Changed my omniauth.rb from this:

OmniAuth.config.logger = Rails.logger

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET'], provider_ignores_state: true
end

to this:

OmniAuth.config.logger = Rails.logger

Also, i defined method def self.find_for_facebook_oauth(auth, signed_in_resource=nil) outside user.rb model (major mistake).

So got it working perfectly now :-)

Hope this helps someone.

Dorian
  • 7,749
  • 4
  • 38
  • 57
user2206724
  • 1,265
  • 3
  • 20
  • 38
  • 2
    Just thought i would let you know that you can load the keys using ENV variables, making it much more secure.. Rails loads its files in alphabetical order so if you create a env.rb file to store your variables then devise.rb is not going to read it as devise config is initialized before the env.rb file, so just create a file that begins with C for example – Richlewis Apr 26 '13 at 21:04
  • Thanks, I had the same mistake like yours in omniauth.rb. I followed another tutorial with manual authentication and required the three lines in omniauth.rb. Moving on to devise, seems like these lines cause the problem. – Bibek Shrestha Aug 14 '13 at 14:51
  • i had the same issue. the problem is about 3 last lines in omniauth.rb – mariomol Mar 08 '15 at 18:20
2

Got it working too :) We don't need to add this code in omniauth.rb

Rails.application.config.middleware.use OmniAuth::Builder do
  provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
end

if we already declare it in devise.rb

require "omniauth-facebook"
config.omniauth :facebook, "APP_ID", "APP_SECRET"
André Herculano
  • 1,258
  • 20
  • 33
0

It helped me to solve a similar problem:

Note: v2.0.1 has an issue with callback url error. You need to add a callback url on config.

config.omniauth :facebook, "APP_ID", "APP_SECRET",
                callback_url: "CALLBACK_URL"

https://github.com/plataformatec/devise/wiki/OmniAuth%3a-Overview

0

Upgrading gem to 4.0.0 and adding require "omniauth-facebook" to devise.rb fixed this for me.

multipolygon
  • 2,194
  • 2
  • 19
  • 23
0

I stack with this problem and no one advice was help me. Problem was in redirect_uri. Devise omniauth gems generated it without https.

Finally resolved this by two steps:

  • Add force_ssl for rails.
  • Do not forget to add proxy_set_header X-Forwarded-Proto https; for nginx config, if you are using it.
Kein
  • 977
  • 2
  • 12
  • 32