protect_from_forgery 的 500 内部服务器错误::null_session
500 internal server error with protect_from_forgery with: :null_session
我正在 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
。
我在这里错过了什么?
只需跳过您不想要的方法的 CSRF 真实性检查,
skip_before_action :verify_authenticity_token, :only => [:logout]
添加不需要 CSRF 真实性检查的方法。
我终于找到了解决办法。
在我的 logout
方法中,我调用 render status: :success
结合 protect_from_forgery with: :null_session
这使得实际状态呈现为 500
。
但是,通过从 logout
函数中完全删除 render status: :success
,我现在得到了预期的 200
。
我想这一定是 Rails 中某个地方的错误?
我正在 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
。
我在这里错过了什么?
只需跳过您不想要的方法的 CSRF 真实性检查,
skip_before_action :verify_authenticity_token, :only => [:logout]
添加不需要 CSRF 真实性检查的方法。
我终于找到了解决办法。
在我的 logout
方法中,我调用 render status: :success
结合 protect_from_forgery with: :null_session
这使得实际状态呈现为 500
。
但是,通过从 logout
函数中完全删除 render status: :success
,我现在得到了预期的 200
。
我想这一定是 Rails 中某个地方的错误?