rails 4 omniauth developer strategy - error on callback - ActionController::InvalidAuthenticityToken in SessionsController#create - ruby-on-rails-4

c9 ide, Ubuntu workspace, rails 4.2.10, ruby 2.4.0
When trying to use omniauth gem in developer mode with developer strategy, login link to 'auth/developer' successfully presents form to user. Upon form submission (where route is 'auth/developer/callback') this error is generated:
ActionController::InvalidAuthenticityToken in SessionsController#create
Would like to be able to use developer strategy during the remainder of application development. Documentation doesn't seem to specify anything else needed for the callback when using the developer strategy (in development mode). There does seem to be at least one small discrepancy in the doc, is something missing as well??
All code working properly when using actual providers or during test mode with cucumber.
Here is portion of initializer code (not including keys/secrets) which I started with in config/initializers/omniauth.rb:
OmniAuth.config.logger = Rails.logger
Rails.application.config.middleware.use OmniAuth::Builder do
provider :developer unless Rails.env.production?
provider :github, 'redacted,'redacted',
{ :name => "github", :scope => ['read:user','user:email']}
provider :facebook, 'redacted', 'redacted'
end
Gemfile includes:
gem 'omniauth'
gem 'omniauth-github'
gem 'omniauth-facebook'
routes.rb:
match 'auth/:provider/callback', :to => 'sessions#create', :via => [:get, :post]
sessions_controller:
def create
begin
authenticator = Authentication.new(env["omniauth.auth"])
authenticator.disallow(session[:user_id]) if session?
authenticator.deny if authenticator.missing_information?
auth, message = authenticator.register_or_login
session[:user_id] = auth.user.id
etc.
app/controllers/sessions_controller/authentication.rb:
def initialize(omniauth)
# get Omniauth authentication hash
#auth_hash = omniauth
end
def auth_hash
#auth_hash
end
etc.
When successful (using other providers or in test mode), callback should be provided with valid token, path of code can then easily be traced through create method of sessions_controller to the constructor of the Authenticator class, etc.
When in development mode using developer strategy, the body of the sessions create method is never entered at all.
After getting valid token, I should see messages such as:
"Welcome <name> You've signed up via <provider>."
However, since error is raised before that point, only see the following in the server output:
Processing by SessionsController#create as HTML
Parameters: {"name"=>"Example User", "email"=>"example#user.com", "provider"=>"developer"}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
actionpack (4.2.10) lib/action_controller/metal/request_forgery_protection.rb:181:in `handle_unverified_request'

I found this in another section of the Wiki:
Rails session is clobbered after callback on Developer strategy
The developer strategy callback is sent using POST request. Disable forgery protection for given action, otherwise session will be clobbered by rails.
skip_before_action :verify_authenticity_token, only: :create
This definitely works, but I still have a few questions.
Is the before_action defined and handled by omniauth itself, or should I add it to my controllers when NOT in developer mode?
It looks as though this scheme works by just adding that line in developer mode, and deleting it in production, which seems pretty unreliable. Is there a way to enforce it automatically instead?

Related

Verification Error with omniauth-facebook in Rails

I have seen many posts about this type of error, but it doesn't seem that any that I can find apply to my case.
This is the error I am getting back from Facebook:
Error validating verification code. Please make sure your redirect_uri is identical to the one you used in the OAuth dialog request
This is the website Site URL I have set up: http://landmark.dev/
This is the redirect URI I have defined: http://landmark.dev/auth/facebook/callback
this is my omniauth.rb (cleaned)
OmniAuth.config.full_host = "http://landmark.dev"
Rails.application.config.middleware.use OmniAuth::Builder do
provider :twitter, 'xxx', 'xxx'
provider :facebook, 'xxx', 'xxx', :scope => 'email'
end
OmniAuth.config.on_failure do |env|
[200, {}, [env['omniauth.error'].inspect]]
end
This is my routes.rb for the callback:
match 'auth/:provider/callback', to: 'sessions#create', via: :all
Twitter works great, by the way - it's just facebook that won't connect. I've been fighting with this for 3 days now and trying to find a solution. Thanks in advance for your help.
UPDATE: While waiting on an answer to this to help figure it out, I tried adding in omniauth-google-oauth2 as authentication through google+ is part of the plan for this project as well. It seems I get the same error from Google:
"error" : "redirect_uri_mismatch"
I would think this indicates some problem on my side, but I have no idea what it could be. The other odd thing is that Twitter still works just fine.
There is a bug introduced in the last update of omniauth-oauth2 gem. Dowgrande your gem version and it should work for while.
gem 'omniauth-oauth2', '~> 1.3.1'
You can see discussion here
https://github.com/intridea/omniauth-oauth2/issues/81
If you are trying this from your local machine (I guess you are doing so because I think that .dev domains are not available at this moment and you should be using a server like POW). The problem is that Facebook can't reach your machine.
You can use a solution like localtunnel http://localtunnel.me/ for development purposes or try to use localhost, I think localhost worked in the past although I'm not sure at this moment.

How do I clear the current session when logging out using devise?

So my application is using Devise to manage authentication. I recently added a logout button to the app and it seemed to work fine redirecting to the login screen. However today I was running some tests on the login screen and found that I was still logged into the app even after using the logout routine.
In my initializer I have:
config.sign_out_via = :delete
My logout link looks like this:
<%= link_to "Log out", destroy_user_session_path, :method => :delete %>
I have a check on ApplicationController to see if the user is required to be logged in:
class ApplicationController < ActionController::Base
before_filter :require_login
...
def after_sign_out_path_for(resource_or_scope)
login_path # displays login page
end
def require_login
redirect_to login_url unless current_user && user_signed_in?
end
For some reason the user_signed_in? check is still returning true even after the clicking the logout link. So I can still go back into the application without having to re-enter my credentials. This obviously shouldn't be the case.
UPDATE:
Here is the output from the server log:
Started DELETE "/users/sign_out" for 127.0.0.1 at 2014-07-03 13:05:07 +1000
Processing by Devise::SessionsController#destroy as HTML
Parameters: {"authenticity_token"=>"Na06x5aAzq/XVhJKrxKEIoh/Bly53fIAq0KEQTG hmM="}
Can't verify CSRF token authenticity
UPDATE 2:
I just noticed now that when I try to log into the app using different login details it isn't working. Since I'm not being logged out it looks like it's skipping the login routine and redirecting me back in. I know that this was working previously so something has changed since to break this functionality.
Okay, so after hours spent trying to figure this out I found two issues.
The first problem was this line in ApplicationController.rb:
protect_from_forgery with: :null_session
I added this some time ago to hide errors if a user tried to log out twice. However, this hid the problem I was experiencing.
The actual issue is an InvalidAuthenticityToken error. It was stopping logging out and also (as I found later) logging in.
To fix the problem I have added the following line (and this is possibly not the correct solution) to ApplicationController.rb:
skip_before_filter :verify_authenticity_token
For some reason I've been experiencing this problem elsewhere in the application and to be honest (I'm new to rails) I've no idea why this error has suddenly started causing me so many headaches.

Production Linkedin Oauth

I'm having an awkward problem using Linkedin gem.
My app tries to get the user data using oauth. On development enviroment it works just fine. But as soon as I upload it to heroku it starts to give me errors like:
2014-07-17T04:25:07.552779+00:00 app[web.1]: NoMethodError (undefined method `picture_urls' for #<LinkedIn::Client:0x007f4f4cea65f8>):
2014-07-17T04:25:07.552783+00:00 app[web.1]: app/models/social_auth.rb:7:in `fetch_details'
The real problem is that it used to work and stopped from nowhere. I even gave a rollback on my git repositories to see if the past code is working but its not.
It seems like it does not answer me correctly even giving the correct callback (I'm sure the error is happening after the oauth validation).
Check the complete code of the definition (that is executed after the model save):
def fetch_details_from_linkedin
client = LinkedIn::Client.new(ENV["LINKEDIN_KEY"], ENV["LINKEDIN_SECRET"])
authkeys = [self.token, self.secret]
client.authorize_from_access(authkeys)
#linkedin = LinkedinUserData.where(user: self.user).first_or_initialize
#linkedin.avatar_url = client.picture_urls.all.first
#linkedin.profile_url = client.profile.site_standard_profile_request.url
#linkedin.save
end
Each item on this model have the token and secret used to validate the user with the 'authorize_from_access' method. I don't know why, but it seems that the callback is answering me an empty object.
Things I already thought about:
Live status on API - CHecked. It gives the error no matter the status of the app on the linkedin api
Callback URL: already checked, even with https. As I said, the callback is being executed. The error is an internal error (500).
I just contacted the developer of the gem and together we discovered that even not specifying the version, heroku for some reason was getting an old version of the gem since github was already on 0.4.7 and it was getting a 0.2.x.
So, I solved this problem by specifying the gem version. Don't know what is happening on heroku, but at least the problem is solved and linkedin is authorizing again.
gem 'linkedin', '0.4.7'
ps: if you get an dependency error, just declare in your gem file:
gem 'hashie', '2.0'
This happens because of an ominiauth dependency.

reset_session not doing anything

I'm building a rails 4 app with JRuby on Torquebox, and running into a weird issue with the sessions. I'm using the devise gem to handle authentication which works well, except that as per the rails security guidelines, I'm trying to reset the session when a user successfully logs in.
I've created a Warden hook which handles this for me, which looks like this
Warden::Manager.after_set_user :event => [:set_user, :authentication] do |record, warden, options|
if options[:scope] && warden.authenticated?(options[:scope])
request = warden.request
Rails.logger.debug "session - #{request.session}"
# backup = request.session.to_hash
# backup.delete(:session_id)
request.reset_session
# request.session.update(backup)
Rails.logger.debug "session - #{request.session}"
end
end
This method is definitely being called which is great, however the two outputs are both the same, and the session is not being reset at all. I'm using the TorqueBox session store, setup like
# session_store.rb
RtsBackend::Application.config.session_store :torquebox_store, {
key: '_RtsBackend_session'
}
# config.ru
use TorqueBox::Session::ServletStore
And it seems to be working as TorqueBox has inserted data, and session data from devise is working, but I just can't seem to clear it.
I was under the impression that devise did this automatically on login, but if it is then the same issue is occurring and rails isn't clearing it.
Any suggestions?
So after digging around, and speaking with one of the core TorqueBox developers, it turned out to be a bug. In rails 4, they changed the way sessions were reset which didn't involve clearing its contents.
Thanks to #bbrowning with this commit it should now be sorted pending a final test once the fix is pushed :)

Error running UAA login.rb sample

I've been investigating a CF deployment scenario in which I have an existing authentication infrastructure, and I need to configure UAA to delegate the login to the existing SSO authority. As a first step I decided to use the login.rb sample server, just to get things going.
I've set up my environment with the sample login.rb and the sample app running on localhost and a UAA instance running on another host. The redirect from the app to the login page at localhost:3000 is working, and looking at my logs I can see that the (pass-through) authentication is successful when the login.rb sample does the post to UAA, and in addition the response received to the post to authorise also gives 200 OK....I can see the JSON with the needed prompt strings is being returned. However, a problem occurs with the erb confirmation dialogue. I'm getting an exception at line 124 of the login.rb
NoMethodError - undefined method `[]' for nil:NilClass:
/home/fieldj1/Documents/workspace-sts-3.1.0.RELEASE/uaa/samples/login/login.rb:124:in `block in <class:LoginApplication>'
/var/lib/gems/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1212:in `call'
/var/lib/gems/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:1212:in `block in compile!'
/var/lib/gems/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:785:in `[]'
/var/lib/gems/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:785:in `block (3 levels) in route!'
/var/lib/gems/1.9.1/gems/sinatra-1.3.2/lib/sinatra/base.rb:801:in `route_eval'
...
The problem seems to be that the code that parses the JSON OAUTH response from UAA is out of date. I fixed it by changing line 124 from this:
erb :confirm, :locals => {:client_id => confirmation_info["authorizationRequest" ["clientId"], \
:scopes => confirmation_info["authorizationRequest"]["scope"]}
to this:
erb :confirm, :locals => {:client_id => confirmation_info["auth_request"]["authorizationParameters"]["client_id"], \
:scopes => confirmation_info["auth_request"]["authorizationParameters"]["scope"]}
Has anyone else seen this? I'm fairly certain that the code I am running should be self-consistent since I did a git clone of the whole UAA. Not sure if my environment is somehow inconsistent, or if I found a real issue.
Thanks,
John
It's a real issue, in the sense that the ruby sample is not up to date, and no-one has got round to updating it because we don't use it anywhere. If you can send a pull request that would be awesome.
We are currently working on updating all our docs and sample app examples, the login ruby sample app that you are using is currently out-dated. You are welcome to make a pull request.
In the meanwhile you can take a look at the new docs, its work in progress : http://cloudfoundry.github.com/.
Thanks,
- Hitesh