title: Logging into Rails 3 app (using Devise for authentication) using ajax on a separate website
body: <p>So, I have a rails 3 application using Devise to handle authentication.  I have another website (all client side javascript) that is trying to log into this rails 3 app using ajax basic authentication, like so:</p>
  
  <pre><code>username = "test@testing.com"
  password = "testing"
  $.ajax({
    'url': '/users/sign_in',
    'otherSettings': 'othervalues',
    'beforeSend': function(xhr) {
      xhr.setRequestHeader("Authorization", "Basic  " + btoa(username + ":" + password))
    },
    sucess: function(result) {
     alert('done');
    }//sicc
  });
  </code></pre>
  
  <p>It hits the route correctly, and I can see that everything looks a-okay on the rails side (the server even thinks it's redirecting), but if I then try to hit a route (using jquery, to load json data) that requires authentication, I get that ugly basic auth javascript pop up telling me I need to authenticate.</p>
  
  <p>Devise obviously doesn't use cookies to store auth data, and from my understanding you can't just access the HttpSession from javascript...is there ANYTHING I can do, or will I just have to use authentication tokens (and write a custom controller to return this to me).</p>
  
  <p>EDIT:</p>
  
  <p>Even a post with basic auth doesn't work, and THAT is weird ('cause in retrospect, yes, it's a post route i'm trying to get to). I get a 401 Unauthenticated error... Why would you need to be authenticated to authenticate?  Having type be 'GET" works just fine, though, but (again, in retrospect) is hitting the 'new' route rather than 'create'.</p>
  
  <pre><code>username = "test@testing.com"
  password = "testing"
  $.ajax({
    'url': '/users/sign_in',
    'type': 'POST',
    'otherSettings': 'othervalues',
    'beforeSend': function(xhr) {
      xhr.setRequestHeader("Authorization", "Basic  " + btoa(username + ":" + password))
    },
    sucess: function(result) {
     alert('done');
    }//sicc
  });
  </code></pre>
  
  <p>EDIT:  Just to confirm, it doesn't seem to be a problem with the "protect_from_forgery" line in the application controller, either...at least, when I comment it out, I still have the same problem.</p>
  
  <p>Nevermind, the problem seems to have been that when I was posting with basic auth, I had a typo in the username, and apparently the way authentication failure is handled is by popping up the basic auth dialogs (very ungraceful, btw)</p>
  
  <h2>Solution:</h2>
  
  <pre><code>username = "test@testing.com"
  password = "testing"
  $.ajax({
    'url': '/users/sign_in',
    'type': 'POST',
    'otherSettings': 'othervalues',
    'beforeSend': function(xhr) {
      xhr.setRequestHeader("Authorization", "Basic  " + btoa(username + ":" + password))
    },
    sucess: function(result) {
     alert('done');
    }//sicc
  });
  </code></pre>