Verification Error with omniauth-facebook in Rails - ruby-on-rails-4

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.

Related

Content Security Policy: Couldn’t parse invalid host http://localhost/static/css

I am using Django with Nginx. My dev enviornment mirrors my prod environment. In development I go through Nginx to access Django in local dev (using docker-compose). Now I am working on making my website more robust security-wise as per Mozilla Observatory. My site it a B right now. The big thing I am working on next is getting the Content Security Policy (CSP) for my website configured. Not only do I want to get my site to an A because gamification, I also want to avoid having XSS attack planes.
After some searching I found Django CSP which looks great. I installed it, added the middleware, and then add some CSP configuration in my settings.py like this:
CSP_DEFAULT_SRC = ("'none'")
CSP_FONT_SRC = ("https://fonts.gstatic.com")
CSP_IMG_SRC = ("'self'", "https://www.google-analytics.com")
CSP_SCRIPT_SRC = (
"'self'",
"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js",
"https://code.jquery.com/jquery-3.2.1.slim.min.js",
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js",
"https://www.google-analytics.com/analytics.js",
"https://www.googletagmanager.com/gtag/js",
"https://www.googletagmanager.com/gtm.js;",
)
CSP_STYLE_SRC = (
"'self'",
"https://fonts.googleapis.com/",
"https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/",
)
I fire up my website in local dev and I see this error message in Firefox dev tools:
Content Security Policy: Couldn’t parse invalid host 'http://localhost/static/css/
Why is localhost invalid? Is it that CSPs do not really work in development? I'd really prefer not to "test my CSP code live" in production if I don't have to. Is there a workaround for this? I have searched a bit and I have not really found anything. This question has the exact error message but it seems to be more related to potential malware in browser extensions. I am guessing there is additional config I can tweak to get the CSP to recognize 'localhost' as valid but I am unsure where to look next. Any help is appreciated! Thanks.
Update: I am now seeing the site work in Dev with the new CSP in Edge, Safari, and Chrome. The only place it is broken is with Firefox. I cleared the cache and did a hard refresh but it is still saying localhost is not valid.

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

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?

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 :)

OAuthException (#368) The action attempted has been deemed abusive or is otherwise disallowed

I'm trying to post a feed on my wall or on the wall on some of my friends using Graph API. I gave all permissions that this application needs, allow them when i make the request from my page, I'm having a valid access token but even though this exception occurs and no feed is posted. My post request looks pretty good, the permissions are given. What do I need to do to show on facebook app that I'm not an abusive person. The last think I did was to dig in my application Auth Dialog to set all permission I need there, and to write why do I need these permissions.
I would be very grateful if you tell me what is going on and point me into the right direction of what do I need to do to fix this problem.
Had the same problem. I figured out that Facebook was refusing my shortlinks, which makes me a bit mad...but I get the point because its possible that shortlinks can be used to promote malicious content...so if you have shortlinks as part of your test, replace them w the full url...
I believe this message is encountered for one of the two reasons :
Your post contains malicious links
You are trying to make a POST request over a non-https connection.
The second one is not confirmed but I have seen that behavior. While same code in my heroku hosted app worked fine, it gave this #368 error on my 000webhost hosted .tk domain which wasn't secured by SSL
Just in case anyone is still struggling with this, the problem occurs when you put URLs or "action links" that are not in your own app domain, if you really need to post to an extarnal page, you'll have to post to your app first, then redirect from there using a script or something. hope that helps.
also it's better in my opinion to use HTTPS links, as sometimes i've seen a behaviour where http links would be rejected, but that's intermittent.
I started noticing that recently as well when running my unit tests. One of the tests I run is submitting a link that I know Facebook has blocked to verify that I handle the error correctly. I used to get this error:
Warning: This Message Contains Blocked Content: Some content in this message has been reported as abusive by Facebook...
But starting on July 4th, I started receiving this error instead:
(#368) The action attempted has been deemed abusive or is otherwise disallowed'
Both errors indicate that Facebook doesn't like what you're publishing.