API使用版本主义gem跳过真实性验证

时间:2014-10-23 23:32:48

标签: jquery ruby-on-rails ruby authentication csrf

我正在尝试为我的Rails应用程序实现验证真实性,这似乎是一个Rails功能

并且无法弄清楚回调失败的位置......

所以这是我的应用控制器:

class ApplicationController < ActionController::Base
  protect_from_forgery
end

这是我的API控制器:

class V1::ManagerLeadsController < ApplicationController
  def create
    manager_lead = ManagerLead.create!(manager_lead_params)
    render json: manager_lead
  end

  private
  def manager_lead_params
    params.require(:manager_lead).permit(:first_name, :last_name, :email, :phone, :company,
       :format, :requested_date, :meeting_type, :has_complited_wholesale_investor_form
    )
  end
end

以下是我的日志:

Started POST "/api/v1/manager_leads" for 127.0.0.1 at 2014-10-24 10:29:46 +1100
Processing by V1::ManagerLeadsController#create as JSON
  Parameters: {"manager_lead"=>{"first_name"=>"", "last_name"=>"", "email"=>"", "phone"=>"", "company"=>"", "meeting_type"=>""}}
Can't verify CSRF token authenticity
   (0.1ms)  BEGIN
  SQL (0.3ms)  INSERT INTO "manager_leads" ("company", "created_at", "email", "first_name", "last_name", "meeting_type", "phone", "updated_at") VALUES ($1, $2, $3, $4, $5, $6, $7, $8) RETURNING "id"  [["company", ""], ["created_at", "2014-10-23 23:29:46.833290"], ["email", ""], ["first_name", ""], ["last_name", ""], ["meeting_type", ""], ["phone", ""], ["updated_at", "2014-10-23 23:29:46.833290"]]
   (7.6ms)  COMMIT
Completed 200 OK in 23ms (Views: 0.4ms | ActiveRecord: 9.4ms)

无法验证CSRF令牌的真实性,但请求是以200OK响应完成的:(

如果我这样做:

if verified_request?
  manager_lead = ManagerLead.create!(manager_lead_params)
  render json: manager_lead
else
  render json: { error: 'Unprocessed entity' }, status: 422
end

然后应用程序开始正常工作:

Started POST "/api/v1/manager_leads" for 127.0.0.1 at 2014-10-24 10:30:59 +1100
Processing by V1::ManagerLeadsController#create as JSON
  Parameters: {"manager_lead"=>{"first_name"=>"", "last_name"=>"", "email"=>"", "phone"=>"", "company"=>"", "meeting_type"=>""}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 3ms (Views: 0.1ms | ActiveRecord: 0.0ms)

我正在使用

Rails 4.1.5
versionist gem
jquery-ui-rails # for form submission

1 个答案:

答案 0 :(得分:0)

好的答案是:

protect_from_forgery with: :exception