OmniAuth Invalid Response Error - ruby-on-rails

I'm using OmniAuth with Devise to allow users to login with facebook or to create a normal account with a username and password. When I originally set it all up I used the excellent directions from Railscasts. Everything was working very nicely for 2+ months but just the other day the facebook login stopped working. OmniAuth sends you away to the authentication with facebook and then returns with: http://localhost:3000/auth/failure?message=invalid_response
Google has no suggestions on what causes this error or how to fix it and the OmniAuth docs don't either. I've tried digging through their code as well but the only mention of this error I've found is this, in /oa-oauth/lib/omniauth/strategies/oauth.rb:
rescue ::MultiJson::DecodeError => e
fail!(:invalid_response, e)
end
Has anyone ever seen this error!? Know what it is or how to fix it?! This is keeping me from launching this application so any help would be very very appreciated!
Thanks,
JG

I've been running into this error in the same situation. Devise is rescuing an unrelated Exception and handling it as an auth failure. I preempted Devise by handling the exception in the controller:
# authentications_controller.rb
def create
omniauth = request.env["omniauth.auth"]
# Blah
# blah
# Blark!
rescue Exception => e
# Just spit out the error message and a backtrace.
render :text => "<html><body><pre>" + e.to_s + "</pre><hr /><pre>" + e.backtrace.join("\n") + "</pre></body></html>"

For anyone else that finds this via google, heroku_backup_task was the culprit for me. When we add that to our gemfile, OmniAuth decoding fails leading to this error. I assume it's some json conflict.
Not sure why it doesn't happen on 1.9.2, but I can confirm that upgrading to 1.9.2 fixes it, but can cause other issues in your app if all your gems don't play nice, and downgrading heroku appears to be a no-go. I'm going to have to destroy and re-create my app now that I've discovered the issue.

Ok,
I'm not sure why this has worked but it has so I'll post here in the effort to help someone else that ends up with this issue.
I upgraded my app to use ruby 1.9.2 (way of the future!) and bang, it just worked again. No idea why but hey sometimes that's just the way it goes.
Upgrading was really easy though. I was sparked into upgrade action by this dhh tweet & found this and this to be really helpful resources in making sure your 1.8.7 code will work in 1.9.2. Props to heroku as well for making it so easy to upgrade an app.

I have had same problem and, I think I find out the solution.
In Tutorial, RailsCast #235 gives authentications_controller.rb
def create
auth = request.env["rack.auth"]
current_user.authentications.find_or_create_by_provider_and_uid(auth['provider'],
auth['uid'])
flash[:notice] = "Authentication successful."
redirect_to authentications_url
end
but,
auth = request.env["rack.auth"]
is no longer exists in omniouth 0.2.3
auth = request.env["omniauth.auth"]
is correct.

OK, so, sorry to post to such an old question, however having followed the Railscasts tutorial for this I was getting the same error. I have come to the conclusion that the error handling of the omniauth-twitter gem is causing the confusion, because it hides the underlying errors. I solved the problem by adding the omniauth-facebook gem to my app and authenticating with this. This quickly uncovered the root error in my app, which was that I had put the User.create_with_omniauth method into the user controller rather than the model, a newbie error but easy to resolve. My error was easy, and somewhat irrelevant, by using the facebook gem, the error handling allowed me to understand the problem and resolve quickly. If you are struggling with this problem, try facebook or another provider and see if you can get to the root problem more easily, and certainly avoiding some of the more complex issues such as upgrades to ruby!

Related

Enabling CORS for IGDB using ruby on rails?

So I've been at this issue for hours now but cannot figure it out. I've been trying to use the IGDB API using the ruby gem igdb_api but keep getting a 403 Forbidden exception. I'm running the server locally for development at localhost:3000. Here is how I setup my test code:
class PagesController < ApplicationController
def home
...
end
def games
# initialize with api_key
Igdb.connect(ENV['IGDB_API_KEY'])
puts Igdb::Game.count
end
end
I've been trying to use rack-cors to fix this but nothing changes. So I'm not sure if I'm missing something obvious. Any help would be great! Thank you.
I don't think cors is an issue.
CORS basically prevents web-browser from making requests to services outside of current domain.
403 errors means some authorization problems.
I ended up using a different gem for accessing the api, one called igdb_client.
While I then had a SSL_connection error since I'm on Windows, it was easily fixed by following this quick solution here: https://superdevresources.com/ssl-error-ruby-gems-windows/.
Hope it'll help anyone in the future!

problems with sign out, cookies and devise on rails

I have been trying to sign in after signing out on my application using devise but I am having an issue with the cookies I think because I have to refresh my web page in order to sign in again. I tried using activerecord-session_store gem and I follow the steps to configure it. I mean, I installed the gem, I generated the recommended migration on the gem documentation and generated the table using rake db:migrate command, I also changes the session_store.rb file but I feel that I am missing something to make it work since I tried it and the same happens. Please help me if you feel I am missing something or if you have other solution for this problem. Many thanks in advance
You are probably getting a "Can't verify CSRF token authenticity" error. Can you check your server logs?
In your ApplicationController please add the following and check if you get an error.
protect_from_forgery with: :exception

CSRF Detection fix provider_ignores_state: true not saving session after successful Devise Omniauth-Facebook Authentication

My application was working ok, and then I updated to Rails 5.0.1. After this my app no longer authenticated with Facebook and came up with the following error in the logs:
Authentication failure! csrf_detected:
OmniAuth::Strategies::OAuth2::CallbackError, csrf_detected | CSRF detected
So, in accordance to what people on StackOverflow suggested, I changed my omniauth config to include the provider_ignores_state: true setting, which suppressed that error.
config.omniauth :facebook, 'xxx', 'xxxxxxxxxxxxx',{
scope: 'public_profile,email,user_birthday,etc...',
info_fields: 'name,first_name,etc...',
provider_ignores_state: true
}
This made everything work just fine; at least in development running locally, but when I pushed the code to my staging server, the app successfully authenticates with Facebook, supposedly "signs" the user in and redirects to root_path() - and then fails authentication and redirects back to users/sign_in.
To help diagnose the problem i put a logging line above the relevant call (to see if it was being executed) such as:
logger.debug " (OmniauthCallbacksController#facebook) about to sign_in_and_redirect with id: #{#user.id} email: #{#user.email} uid: #{#user.provider_uid}"
sign_in_and_redirect #user, event: :authentication
My OmniauthCallbacksController handler for the Facebook provider there for does seem to reach 'sign_in_and_redirect' - but for reasons I cannot determine on my staging environment, it never actually saves the session to a cookie. There are no errors in the logs (in debug mode) to demonstrate there was any kind of exception thrown - except that the query to increment the log_in_count on the user doesn't actually run any query:
(2.4ms) COMMIT
(0.2ms) BEGIN
(0.2ms) COMMIT
Which looks weird (no actual update query, whereas in development i can see the log_in_count etc be incremented). But its the only other indication that something goes wrong. After that, it fails the authenticate_user! check and redirects back to the sign_in_url.
This is sending me mad - Is this a bug, or is there a fix for this issue?
We had the same error come up for omniauth-github. What fixed it for us (aside from the provider_ignores_state: true hack) was the URL in the link to github's authentication site. Originally we'd entered the entire URL for github OAuth (https://github.com/login/oauth/authorize?client_id=#{ENV["GITHUB_CLIENT_ID"]}&scope=repo), but changing it to the omniauth format of just /auth/github fixed this CSRF error (as well as a no route found error when we tried mocking out / testing our OAuth). Leaving this here in case anyone else has a similar issue in the future!
I was finally able to solve this issue, but I still don't understand WHAT went wrong. Basically, created a "empty" Rails 5 project and setup a brand new devise using the omniauth-facebook gem and settings for my main app - deployed to a cloned instance of the staging server and it worked! Most of the code was the same; but when I replaced the devise.rb initializer with the one from the new app, the old code proceeded to work on the stagingg server again. Interestingly, I coped the Omniauth config from the old one to the new app, so it must have been something wrong with another of Devise's modules...and not with Omniauth itself.
In either case, it's working now. So I will put this to bed and leave this here in case another person encounters the same problem; and while I cant say what was specifically wrong, these are the steps I used to debug/fix my particular problem.

Authlogic_oauth2 alternative for Rails 2.3

In order to let users signup and login using facebook I used the authlogic_oauth2 gem (v.1.1.2) along with oauth2 (v. 0.0.10) and authlogic (2.1.6) in a Rails 2.3 application.
Everything worked well for more than 2 years but from a month or so, users are not able to login or signup with Facebook anymore.
I don't know what happened but I didn't changed anything so it seems that Facebook changed something on their end and authlogic_oauth2 doesn't seem to be able to work anymore.
Which could be the easiest way to fix the issue and bring back user login/signup with facebook?
Is there any better gem to help on the job?
Thanks in advance,
Augusto
I doubt that you may have done some changes in your present application unknowingly that caused the login and logout failures.
One possible cause of the problem might be the redirections from: http://yoursite.com to http://www.yoursite.com based on the changes that you made. Check the blog that mentions this problem.
The fix is to set: config.action_controller.session[:domain] = '.YOURDOMAIN.COM' inside of environment.rb (Make sure to prefix it with the .). That will make cookies work for both www.yourdomain.com and yourdomain.com (as well as any other subdomains).
I also recommend to check the login behavior in different environments: Development and Production and then check the output in the log files clearly.
This may help you to tweak the problem domain, as you mentioned that your code was working previously.
Update:
there is an update in facebook oauth and it is mentioned that all applications need to be updated to the latest version of oauth.
So that is the possible cause for your problem.
It outlines a plan requiring all sites and apps to migrate to OAuth 2.0, process the signed_request parameter, and obtain an SSL certificate by October 1.
check the link below:
http://developers.facebook.com/blog/post/497/
Thanks!
I found the solution: Omniauth works perfectly fine with Rails 2.3 and there is even a demo app on how to integrate it with Authlogic.
A popular one would be Devise which plays well with Omniauth. I am not sure of the compatibilities with rails 2 though, maybe time to upgrade...
Any reason you can not use Koala? https://github.com/arsduo/koala

NoMethodError when attempting to use open_id_authentication

I'm currently adding OpenID login support for a Rails 3.0.0 application.
I have already installed ruby-openid (the gem) and open_id_authentication (the plugin). However, after following the steps required to set up both (from the READMEs), I am still getting this error:
undefined method `authenticate_with_open_id'
I tried Googling the problem, but most threads seem to date from years ago and remain suspiciously unanswered.
Am I missing something obvious? What is causing this problem? Note that I have had no problems switching to file-based stores in environment.rb, so I am sure that the plugin is correctly installed.
Update: Some unresolved problems of the same nature:
http://railsforum.com/viewtopic.php?id=23151
Experiencing a similar error; oddly, I have this working on Rails 3.2 on another branch, and can't figure out the difference; anyhow I found that I got a little further by following suggestions here: Rails 3.0.9 + open_id_authentication
That is, adding the line include OpenIdAuthentication after class SessionsController < ApplicationController:
class SessionsController < ApplicationController
include OpenIdAuthentication
But now I get a Completed 401 Unauthorized in my log, and see a blank page -- just and tags. Ugh.
Update: Ooh, got further; I followed this post: open_id_authentication - "OpenIdAuthentication.store is nil. Using in-memory store." problem
and as they suggested, "added an initializer named config/initializers/openid.rb with this inside":
require 'open_id_authentication' # this was needed, but not described in the referred-to post
OpenIdAuthentication.store = :file
I was then directed to the OpenId provider and was able to click "allow", but on returning to my app, I now see:
NoMethodError in SessionsController#create
undefined method `encoding' for nil:NilClass
Anyhow, finally, I found a restful routes problem and fixed that, and now logging in works!

Resources