I was helping a friend integrate an API into the application. He is running Rails 2.3.4 with Authlogic. His authentication check method was the following:
1 2 3 4 5 6 7 8 | def require_user unless current_user session[:return_to] = request.request_uri flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url return false end end |
Although this worked great for the HTML requests, the XML requests were getting HTML response with a redirect to the login page. Not what we were looking for. Instead, the require_user method needed to be aware of the mime-type and return an appropriate response.
Here is the block that responds to the mime-type. Instead of getting an HTML response to an XML request, an XML error reponse with the correct HTTP status code is returned.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | def require_user unless current_user respond_to do |format| format.html { session[:return_to] = request.request_uri flash[:notice] = "You must be logged in to access this page" redirect_to new_user_session_url } format.xml { user = User.new user.errors.add_to_base("Authentication is required.") render :xml => user.errors, :status => 401 } end return false end end |

I’ve been having issues with this exact same problem. I knew there was an easy answer… Thanks!