要禁用CSRF protection,您可以像这样编辑您的ApplicationController:
class ApplicationController < ActionController::Base
protect_from_forgery with: :null_session
# ...
end
或禁用特定控制器的CSRF protection:
class ProfilesController < ApplicationController
skip_before_action :verify_authenticity_token
# ...
end
:null_session 策略清空会话而不是引发异常非常适合 API。因为会话是空的,所以不能使用current_user 方法或引用session 的其他助手。
重要提示:
要处理标准请求(通过 html 表单)和 API 请求,通常您必须为同一资源设置两个不同的控制器。示例:
路线
Rails.application.routes.draw do
resources :profiles
namespace :api do
namespace :v1 do
resources :profiles
end
end
end
应用控制器
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
end
ProfilesController
(html 请求的标准控制器)
# app/controllers/profiles_controller.rb
class ProfilesController < ApplicationController
# POST yoursites.com/profiles
def create
end
end
Api::V1::ProfilesController
(API 请求的控制器)
# app/controllers/api/v1/profiles_controller.rb
module Api
module V1
class ProfilesController < ApplicationController
# To allow only json request
protect_from_forgery with: :null_session, if: Proc.new {|c| c.request.format.json? }
# POST yoursites.com/api/v1/profiles
def create
end
end
end
end
推荐人:
http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html#method-i-protect_from_forgery