Devise omniauth-github oauth2 error "bad_verification_code" - ruby-on-rails

I have a Rails 3.1 app with devise 1.5.3, omniauth 1.0.1, and omniauth-github 1.0.1 as well.
config/initializers/devise.rb
config.omniauth :github, ENV['GITHUB_KEY'], ENV['GITHUB_SECRET']
config/routes.rb
devise_for :users, :controllers => { :omniauth_callbacks => "users/omniauth_callbacks" } do
get '/users/auth/:provider' => 'users/omniauth_callbacks#passthru'
end
The key and secret are set up as Heroku variables and the application is registered on Github. Clicking the link you are sent to Github, authenticated and then sent back to the Github callback route with the code and all the info that the auth succeeded.
The problem is that it is getting picked up by the failure method of the users/omniiauth_callbacks controller. I added some put statements to see what the env['omniauth'] was getting sent back with.
env['omniauth.auth'] has all of the info from Github that it is supposed to.
env['omniauth.error'].response however is a an OAuth2::Response with a lot of info, the important parts being:
#parsed={"error"=>"bad_verification_code"}, #error=#<OAuth2::Error: OAuth2::Error>
I am wondering if this post is still valid since Github now has their new v3 API.
It would be possible to just put the code I need in the failure method of the callback controller but that feels kind of dirty and hackish.
Any suggestions would be much appreciated.

I am not really sure if this is going to help, but only yesterday when i was trying to authenticate with github using omniauth gem, i kinda was getting the same errors.
In the end, i ended up doing it the github way of sending the client_id,client_secret and redirect_uri to /github.com/oauth/authorize and got the callback on the redirect_uri.
Heres the link

Related

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.

Getting 400 error when trying to get auth token - twitter omniauth

I've got a rails app in which I am trying to implement twitter omniauth so many users can post/get to/from many twitter accounts from within the app. I have followed the railscasts (until about 3 minutes in) on the topic exactly yet am getting a 400 http response.
In my gemfile:
gem 'omniauth'
gem 'omniauth-twitter'
In /config/initializers/omniauth.rb
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'],
end
In my view I naturally have <%= link_to "Connect", "/auth/twitter" %> and in my routes.rb I have (this is the only difference to the railscast as I am not using it to signup/login users but rather to post to twitter):
get 'auth/:provider/callback', to: 'twitter_accounts#create'
get 'auth/failure', to: redirect('/')
Clicking the link in the view results in the following error:
OAuth::Unauthorized
400 Bad Request
As far as I can see my api key & secret are correct so it seems that it is not setting the http header correctly. The request and response params are empty on the rails error page. Any help would be greatly appreciated.
So as usual after tearing my hair out all day I got it to work the minute I post the question here. The issue was it was not picking up my environment variables. I had pasted in the strings directly to see if this was the problem however this also required a restart of the rails app to take effect which I had not done.
Just to extend on the answer of rorykoehler, you may also need to restart your terminal for it to pick up the environmental variables of your OAuth key and secret. If you have them stored in your bash profile you can just run
source ~/.bash_profile
in your terminal for it to pick it up.
If you are running your code in an IDE like RubyMine or Visual Studio Code you may need to restart your IDE.
Just change
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, ENV['TWITTER_KEY'], ENV['TWITTER_SECRET'],
end
with
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, 'TWITTER_KEY', 'TWITTER_SECRET'
end

EmberJS Refresh page requires user to login

Trying to help out with an Ember app built on rails. When the user refreshes the page the page I lose the session. Chrome Console shows that the local store is cleared thereby eliminating the token.
I am not even sure where to begin in posting code but will gladly post some in response to a request.
Rails 4.1
Devise 3.2.4
Simple_token_authentication 1.2.1
ember-simple-auth 0.4.0
UPDATE
If for some reason you need to stay on 0.4.0 you can change your call. Until the patch came out we were doing this:
:auth_token => user.authentication_token, :auth_email => user.email, :access_token => user.authentication_token, :token_type => "bearer"
Not the most elegant and the only reason we were doing it was because logging out on refresh was annoying the bleep out of us.
That behavior is caused by a bug in Ember.SimpleAuth. It already has been fix; the fix will be included in the 0.5.0 release which will be released later today or tomorrow.

can't authenticate with Facebook

I'm following Ryan Bate's instructions for using Omniauth to set up third party authentication, except that I'm trying it with Facebook rather than Twitter, which he sets up in RailsCast 235.
After installing omniauth-facebook gem, and setting up the initializer
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'APP_ID', 'APP_SECRET'
end
I should be able to go to localhost:3000/auth/facebook and be presented with the Facebook login (even though it won't eventually work because we haven't set up the callback url yet) However, when i go to that url, I get this error
{
"error": {
"message": "Error validating application.",
"type": "OAuthException",
"code": 101
}
}
and the url actually changes to
https://graph.facebook.com/oauth/authorize?response_type=code&client_id=APP_ID&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Ffacebook%2Fcallback&scope=email%2Coffline_access
On my app, I've set up Devise and followed the instructions on the Devise wiki for integrating Facebook authorization https://github.com/plataformatec/devise/wiki/OmniAuth:-Overview
Can anyone tell me what the problem might be?
Doing a Google search on the error message revealed that quite a few people have experienced this problem in recent weeks but couldn't find anyone with a solution
I searched for 101 and I stumbled upon this page. As you can see, that error stands for Invalid API key, so I believe that the problem lies in where you defined your key.
You should set up your key and your secret in a separate file (for clarity and security) but be mindful that Rails loads files in alphabetical order so the file that defines those constants should have a name that comes before the file that configures the oauth connection. In my case, I created a file called constants.rb, which comes before devise.rb. Also, make sure to keep this file away from source control. You don't want other people to have your keys and secrets.
# config/initializers/constants.rb
FACEBOOK_KEY = 'string'
FACEBOOK_SECRET = 'string'
Then configure your connection in your devise file if you are using devise or in your omniauth file if you are using simple omniauth:
# config/initializers/devise.rb|omniauth.rb
require 'omniauth-facebook'
config.omniauth :facebook, FACEBOOK_KEY, FACEBOOK_SECRET
Now, there is a better way to do this using ENV variables. I recommend the Figaro gem as it really simplifies configuring apps.
If you want to display the facebook dialog page as a popup, you'll want to use
config.omniauth :facebook, FACEBOOK_KEY, FACEBOOK_SECRET, :display => 'popup'
And follow this question later down the road.
And, if you are on Windows, you'll need a certificate so that the SSL connection does not fail. The solution to this problem is clarified by Arcolye here.
Finally, to test your login locally, all you need to do is define your Site URL as http://localhost:3000/. That's all there is. You do not have to define your canvas URL.
In the past, I had an issue using localhost with Facebook applications. What I ended up doing was to create an entry in my host file on my computer to point fbdev.com to localhost and just used "fbdev.com" in place of localhost in the app settings on facebook.
I was getting the same error but I had forgotten to restart the server after adding my APP_ID and APP_SECRET :-P
Maybe that will help?
First, ensure you have the following in routes.rb:
# Auth callback routes
match '/auth/:provider/callback' => 'sessions#create' # This route is hit when a user gives the app permissions (the auth hash will be in request.env['omniauth.auth'])
match '/auth/failure' => 'sessions#failure' # This route is hit when a user doesn't give the app permissions
Second, ensure you have the following in config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do
provider :facebook, 'APP_ID', 'APP_SECRET', :scope => 'email', :display => 'page'
end
Third, ensure you have http://localhost:3000/ set as your Canvas URL in your Facebook app settings (https://developers.facebook.com/apps/).
You should then be able to simply redirect your users to http://localhost:3000/auth/facebook to display the authentication dialog to them.

rails3 devise - no route matches "/sessions/user"

it is the first time I am working with devise and I am a confused by the massive amount of files and configuration options.
Before installing devise, I used the nifty:authentication from ryan bates - which I didn't delete before installing devise and I guess now my routes and/or controllers are a little screwed up.
well, after singing in on /users/sign_in devise tries to redirect me to
http://localhost:3000/sessions/user
but I get the error:
No route matches "/sessions/user"
I don't know where is the error, any help appreciated
I put all the relevant code in a gist: https://gist.github.com/972058
thanks in advance
In my case, I had a session controller which was causing issues. Removing resources :sessions from the routes file should solve the problem. That was because I had previously created a session manager. Once gone, I did not see the issue again.
That's because you don't have root path in your routes. As you can read in devise page: https://github.com/plataformatec/devise
After signing in a user, confirming
the account or updating the password,
Devise will look for a scoped root
path to redirect. Example: For a :user
resource, it will use user_root_path
if it exists, otherwise default
root_path will be used. This means
that you need to set the root inside
your routes
To specify redirect page you need to do this https://github.com/plataformatec/devise/wiki/How-To:-Redirect-to-a-specific-page-on-successful-sign-in
btw. you don't need sessions controller to make it works

Resources