3

Devise has been my go to authentication plugin for the past few Rails 3 projects I've worked on. In the current project, I'm using a vanilla install of devise with a user model using the default configuration modules.

Whenever I click a link that does an ajax post to a controller that uses Devise's:

before_filter :authenticate_user!

it prompts me for basic authentication. I've never seen this happen before, and I was wondering if anyone has an idea as to what might be causing it.

Todd Yemen
  • 33
  • 2

2 Answers2

3

AJAX is going to be (usually) a content_type of javascript or json.

In cases like this, devise is not going to redirect you to the login page, it will issue a 401 response code (login required). Your browser gets the 401 and gives you the change to login with HTTP authentication.

You will probably want to check on your view if the user is logged in before sending the ajax information to the protected endpoint.

Jesse Wolgamott
  • 40,197
  • 4
  • 83
  • 109
  • Also in jQuery .ajax you can listen for the response code, and handle the 401 there (either pop up a login form, redirect, or just tell the user to login first) – Jesse Wolgamott Apr 27 '11 at 12:26
  • The thing is though that I am already logged in when making the ajax request. – Todd Yemen Apr 27 '11 at 15:40
  • you could try removing :authenticate_user! and seeing if you have a "current_user" in the controller after the request. But that's your issue – Jesse Wolgamott Apr 27 '11 at 15:52
  • I removed authenticate_user!, signed in, verified that I was actually signed in, made the ajax request and it still prompts me for basic auth. – Todd Yemen Apr 27 '11 at 15:57
  • problem is likely in your ajax call then. It's either going to a different domain, or you have a setting wrong. check out http://stackoverflow.com/questions/1041285/does-jquery-send-cookies-in-a-post – Jesse Wolgamott Apr 27 '11 at 16:05
1

http://jasoncodes.com/posts/rails-csrf-vulnerability

The above link mentions that Rails requires an auth token with all "with each non-GET Ajax request"s to Devise. (because of the protection from forgery stuff)

The article mentions how to do it, too, but I'm still figuring that part out.

If you DON'T do that, then Rails seems to require you to log in a second time (usually only once).

J.R.
  • 5,789
  • 11
  • 55
  • 78