Devise throwing HTTP auth on XHR and logging out

2019-05-07 09:41发布

问题:

I'm having a ton of issues with Devise, using OmniAuth, to authenticate my Rails app. I relaunch my server and open up a new tab in Incognito mode (so that the cookies are cleared) and load my app. I log in, and then go through to the app.

When I get to a page that calls an authenticated action via AJAX, it asks for a username and password via HTTP Basic Authentication. I've disabled this in my devise.rb.

config.http_authenticatable = false
config.http_authenticatable_on_xhr = false

When I then go back to a previous page, it redirects me to the login page and asks for a login. This also happens when I visit a page that doesn't require authentication and then go back to an authenticated page.

This is getting immensely frustrating. I've unpacked Devise and Warden to my vendor/gems directory so that I can try to debug it, but I honestly can't figure out where to begin. Any help would be hugely appreciated.

回答1:

Your AJAX call probably isn't setting the CSRF token. You might need to update your UJS gem (jquery-rails probably) or manually set the X-CSRF-Token HTTP header to the value of the tag. See this question: Devise session immediately expiring on .js call [AJAX]. You can test if this is the problem by disabling CSRF protection temporarily by chucking config.allow_forgery_protection = false in config/application.rb.

If you go the manual route, you should probably grab the value of the 'authenticity_token' meta tag first, and use that as the name of the actual token meta tag, rather than hard coding the reference to 'csrf-token'.

I would recommend updating to Rails 3.0.10 or 3.1 if you can. I was still having problems on 3.0.7.