使用protect_from_forgery时出现500内部服务器错误:: null_session

时间:2016-01-18 11:38:13

标签: ruby-on-rails-4 csrf-protection

我正在Rails 4中构建一个JSON API但是我遇到了CSRF真实性检查的问题。 我已将它们全部禁用:

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

我的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

我可以正确登录,我的注销视图按预期呈现正确的输出,但我仍然得到500 Internal Server Error。我的日志说:

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)

我期待获得Completed 200 OK

我在这里错过了什么?

2 个答案:

答案 0 :(得分:1)

我终于找到了解决方案。

logout方法中,我致电render status: :success

结合protect_from_forgery with: :null_session,这使得实际状态呈现为500。 但是,从render status: :success函数中完全删除logout,我现在可以按预期获得200

我想这一定是Rails中的某个bug?

答案 1 :(得分:0)

跳过CSRF真实性检查,了解您不想要的方法,

skip_before_action :verify_authenticity_token, :only => [:logout]

添加您不希望CSRF真实性检查的方法。