Search code examples
ruby-on-rails-4csrf-protection

500 internal server error with protect_from_forgery with: :null_session


I'm building a JSON API in Rails 4 but I'm having trouble with CSRF authenticity check. I've disabled it all together with:

class ApplicationController < ActionController::Base
  protect_from_forgery with: :null_session
end

My UsersController:

class UsersController < ApplicationController
  skip_before_action :require_current_user!, only: [:login]

  def login
    username = params[:username]
    password = params[:password]

    begin
      @user = authenticate(username, password)
    rescue AuthenticationException
      render status: :unauthorized
    end
  end

  def logout
    log_out!
    render status: :success
  end
end

I can login correctly and my logout views renders as expected with correct output, but I'm still getting a 500 Internal Server Error. My log says:

Started POST "/logout.json" for ::1 at 2016-01-18 12:17:04 +0100
Processing by UsersController#logout as JSON
Can't verify CSRF token authenticity
  Rendered users/logout.json.jbuilder (0.1ms)
Completed 500 Internal Server Error in 9ms (Views: 7.3ms | ActiveRecord: 0.0ms)

I'm expecting to get a Completed 200 OK.

What I'm I missing here?


Solution

  • I finally found a solution.

    In my logout method i call render status: :success

    Combined with protect_from_forgery with: :null_session this makes the actual status render to 500. But by removing render status: :success entirely from the logout function I now get 200 as expected.

    I guess this must be a bug somewhere in Rails?