I have a simple rails app with a single controller. I have a “before filter” for some of the methods of my controller, where I check if the user is logged in by looking at the session object:
@user = User.where(:id => session[:user_id]) if session[:user_id]
In a “login” method of my controller, I do:
session[:user_id] = user.id
Pretty usual stuff. If I access my app from a web browser (Chrome), everything works fine. However, when I use NSURLRequest from my iOS app to access my rails app, the server always creates a new session for each request. It never seems to be able to identify the existing session, even though the request is sending the cookie with the proper session ID in it. In fact, if I look at the “cookies” object in my rails app, I can see it contains the session ID. However, the session object is always empty! Not sure why the server is not able to retrieve the session. I’m using Passenger Phusion. Any suggestions?
If you are
POSTing to your login page, and the post does not include a CSRF token matching the token in the session, then Rails will fail the request and invalidate/reset the session as a security precaution.To fix it, simply read the CSRF token out of the session and include it in your request, or turn off CSRF token checking, you can place
skip_before_filter :verify_authenticity_tokenin your controller to skip the CSRF protection checks. Note that the latter approach does open potential security holes, so including the tokens and checking them is recommended if it is at all viable.