Reputation: 2284
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?
Upvotes: 2
Views: 615
Reputation: 2284
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?
Upvotes: 1
Reputation: 761
Just skip the CSRF authenticity check for the methods you don't want to,
skip_before_action :verify_authenticity_token, :only => [:logout]
Add the methods to which you don't want the CSRF authenticity check.
Upvotes: 0