Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS error on redirect? #356

Closed
firrae opened this issue Feb 8, 2021 · 13 comments
Closed

CORS error on redirect? #356

firrae opened this issue Feb 8, 2021 · 13 comments

Comments

@firrae
Copy link

firrae commented Feb 8, 2021

Hi there,

I've tried reaching out for help in a number of places so far with little to no replies so hopefully this is fine to reach out here. I have a SO if you know the answer and want the points there feel free to answer and I'll accept: https://stackoverflow.com/questions/66085378/devise-omniauth-facebook-login-stuck-with-cors-issue.

Synopsis of the issue is I set up Omniauth-Facebook alongside Devise as the Devise documentation laid out. It seems to be generating all the routes expected, and the server is showing the POST request to initiate, but when the server responds with the redirect I get a CORS error in return:

Access to fetch at 'https://www.facebook.com/v4.0/dialog/oauth?client_id=<client_id>&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fauth%2Ffacebook%2Fcallback&response_type=code&scope=email&state=511bb14a4b678404f0fc4fc4b52a641439077a27ecd5dac4' (redirected from 'http://localhost:3000/auth/auth/facebook') from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

From there I went and tried the Rack-CORS package, but that didn't seem to do much, and honestly it seems more for incoming requests than outgoing like this issue seems to be. But none the less I tried it to no change.

I am just using ERB templates as I intended to use Hotwire (Turbo), so there shouldn't be any extra JS going on in my repo. I feel like it shouldn't be needed, but maybe there is?

I have the code I am running here: https://github.com/firrae/devise-omniauth-facebook-CORS-error-example.

I'm sure it's something really dumb at this point, but after 2 days of looking I just don't see it. If anyone can point it out, or at least point me in the right direction it would be greatly appreciated.

@swiknaba
Copy link
Contributor

swiknaba commented Feb 9, 2021

You are not stupid, it is the same issue I have laid out here: #345, also discussed at #343.

This library will by default return a 500 error unless you change a setting. This is horrible, however, my PR to correct the default settings to a sane default here: #345 got no attention 🤷‍♂️

here:
https://github.com/firrae/devise-omniauth-facebook-CORS-error-example/blob/4aef2fa7a3faef8330a3193a349f8bcdd82fb659/app/models/user.rb#L13

user.image = auth.info.image

you are trying to load the image which is done over http without SSL, which the facebook API rejects already since some years.

@simi maybe you want to reopen that PR.

@firrae
Copy link
Author

firrae commented Feb 9, 2021

@swiknaba thanks for the input. While that might have eventually become an issue this CORS issue is happening before even getting to the login screen. It happens when the server returns the redirect to the Facebook login endpoint and then complains that the redirect is going to another domain.

I set the config to:

config.omniauth :facebook, "<client_id>", "<client_secret>", secure_image_url: true

This creates the same error.

Any other ideas?

EDIT: I also tried even doing display: 'popup' and getting the same error.

@simi
Copy link
Owner

simi commented Feb 9, 2021

@swiknaba hello. I'm not sure if I follow this, but #345 is not actual pull request, but issue and I have replied in there I would welcome that change if anyone can provide pull request. There was no additional response and thus it was closed due to inactivity. So feel free to open pull request regarding that one.

@firrae
Copy link
Author

firrae commented Feb 9, 2021

Some more info, when I remove the POST method from the link it at least tries to do something but still ultimately fails, but I'm pretty sure it's the client flow, which is not my goal. When I use POST it still returns the redirect error.

Also I find that the default Devise login screen seems to use the GET method (client side flow) by default and not the server side?

Any thought @simi?

@firrae
Copy link
Author

firrae commented Feb 9, 2021

Also pretty sure it’s #346 that is the PR @swiknaba referenced. But this does not solve my issue.

@swiknaba
Copy link
Contributor

swiknaba commented Feb 9, 2021

@simi Sorry for being a bit harsh yesterday, it was a frustrating day.

looking at the URL, it seems you are still using graph version 4. That is still supported, but you could try using e.g. v8 or v9. See: https://developers.facebook.com/docs/graph-api/changelog -> I am using v8 for all projects, and besides the image-URL problem I've never had issues with this gem.

https://github.com/firrae/devise-omniauth-facebook-CORS-error-example/blob/master/config/initializers/devise.rb#L275

here is my usual initializers/devise config

  config.omniauth :facebook,
                  Rails.application.credentials.facebook[:app_id],
                  Rails.application.credentials.facebook[:secret],
                  token_params: { parse: :json },
                  client_options: { site: 'https://graph.facebook.com/v8.0', authorize_url: 'https://www.facebook.com/v8.0/dialog/oauth' },
                  secure_image_url: true, # enforces generating a https url for the profile image download
                  image_size: 'large' # 200px wide, variable height

Did you properly set up facebook? Go to https:// developers.facebook.com/apps/XXXX/settings/basic/ -> xxx is your app-id

You'll have to configure the API version of Graph that you are using, and also set "App Domains" to all domains that you are using. Are you using this from localhost by any chance? Also double check on your app id + secret.

You should not set origins '*' in cors. Instead, e.g. put a regex there sth. like

origins(%r{\Ahttps?://([a-zA-Z\d-]+\.){0,}your-domain\.(com|de|eu)\z})

you could also try setting credentials: true in cors, i.e.

resource '*',
         headers: :any,
         credentials: true, # does not work in conjunction with "any" origin, i.e. '*'. Also adjust in your FE.
         methods: %i[get put post options patch delete]
end

@firrae
Copy link
Author

firrae commented Feb 9, 2021

@swiknaba Do you use the client flow or the server flow? Using your config it seems to be trying to use the correct API version (V9.0). The V4 was the default generated as I didn't change anything. App ID and Secret are correct, but I'm still getting the following:
image

This happens as soon as I click my link generated by:

<%= link_to "Sign in with Facebook", user_facebook_omniauth_authorize_path, method: :post %>

Using a button leads to the same error. CLI shows the following log on link/button press but after nothing:

[2021-02-09T01:44:11.381259 #9490] DEBUG -- omniauth: (facebook) Request phase initiated.

I personally didn't want to set up CORS, I just saw someone say it helped them with a somewhat tangential issue so I figured I might as well try. I plan to remove it if I can afterwards.

Any other thoughts or things I can try to debug further?

@firrae
Copy link
Author

firrae commented Feb 10, 2021

OK, something I thought to try, but turning off the JS I at least get a little further it seems? Specifically I found removing the import from hotwire-turbo got me to the point below. Pressing the POST link generated it returns me to:

http://localhost:3000/auth/login#_=_

CLI:

Started POST "/auth/auth/facebook" for 127.0.0.1 at 2021-02-09 01:51:38 -0500
D, [2021-02-09T01:51:38.465385 #11607] DEBUG -- omniauth: (facebook) Request phase initiated.
Started GET "/auth/auth/facebook/callback?code=<a JWT>" for 127.0.0.1 at 2021-02-09 01:51:38 -0500
D, [2021-02-09T01:51:38.769075 #11607] DEBUG -- omniauth: (facebook) Callback phase initiated.
Processing by Users::OmniauthCallbacksController#facebook as HTML
  Parameters: {"code"=>"<same JWT>", "state" => "<state variable>"}
  User Load (4.5ms)  SELECT "users".* FROM "users" WHERE "users"."provider" = $1 AND "users"."uid" = $2 ORDER BY "users"."id" ASC LIMIT $3  [["provider", "facebook"], ["uid", "10157923871113581"], ["LIMIT", 1]]
  ↳ app/models/user.rb:9:in `from_omniauth'
Completed 500 Internal Server Error in 348ms (ActiveRecord: 29.6ms | Allocations: 10929)


E, [2021-02-09T01:51:39.576743 #11607] ERROR -- omniauth: (facebook) Authentication failure! undefined method `name=' for #<User:0x000056366ec34d08>: NoMethodError, undefined method `name=' for #<User:0x000056366ec34d08>
Processing by Users::OmniauthCallbacksController#failure as HTML
  Parameters: {"code"=>"<the JWT>", "state"=>"<same state>"}
Redirected to http://localhost:3000/auth/login
Completed 302 Found in 2ms (ActiveRecord: 0.0ms | Allocations: 2354)

That seems like it's at least doing something? Seems like maybe the way Hotwire-Turbo is intercepting links is causing an initial issue?

@firrae
Copy link
Author

firrae commented Feb 10, 2021

OK, making it a button and putting Turbo's 'data-turbo: "false"` tag on the button seems to get me to the same place as having disabled it. So I guess now hopefully onto the next thing? For the moment I'll keep this open while I try and figure out this new point of error just in case more comes up related to this.

Thank you both for at least trying to help, it just ended up being something I didn't even think would interact with it until I ran into a REALLY off the beaten path comment about forms with Turbo.

ex.

<h1>Hello World</h1>

<% if user_signed_in? %>
  <%= link_to('Logout', destroy_user_session_path, method: :delete) %>
<% else %>
  <%= link_to('Login', new_user_session_path) %>
  <%= button_to "Sign in with Facebook", user_facebook_omniauth_authorize_path, :data => {turbo: "false"} %>
<% end %>

You can actually put the :data => {turbo: "false"} on an outer div as well and get the same result.

I plan to structure out the baseline of my app and maybe make a template if I find it works for me.

@swiknaba
Copy link
Contributor

swiknaba commented Feb 10, 2021

E, [2021-02-09T01:51:39.576743 #11607] ERROR -- omniauth: (facebook) Authentication failure! undefined method name=' for #<User:0x000056366ec34d08>: NoMethodError, undefined method name=' for #User:0x000056366ec34d08

this is an error in your app. Have a look at your schema: https://github.com/firrae/devise-omniauth-facebook-CORS-error-example/blob/master/db/schema.rb
Your users table does not have name, yet you try to set it here: https://github.com/firrae/devise-omniauth-facebook-CORS-error-example/blob/master/app/models/user.rb#L12

I use https://github.com/ctran/annotate_models/ to automatically have the database schema on top of my models, which makes it easy to be aware of all your properties.

I use the omniauth path helper: omniauth_authorize_path(:user, :facebook) in my view templates.

@firrae
Copy link
Author

firrae commented Feb 12, 2021

@swiknaba yes, I fixed most of the issues and figured out what I needed. I plan on taking what I got working and using it as the foundation to designing my actual DB layout and going forward. Thanks to you both!

(Also that Gem seems pretty useful, thanks for that as well!)

@firrae
Copy link
Author

firrae commented Feb 12, 2021

@simi this seems to be coming up in other places, but my title doesn't cover it well so it doesn't come up in Google and such clearly. Would you prefer I change the title?

I also plan on submitting a PR to the documentation to help clarify this caveat with Hotwire/Turbo. Is there a specific place you'd prefer it put?

@github-actions
Copy link

This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

3 participants