摆脱Rails中的X-CSRF-Token

时间:2012-11-16 01:19:02

标签: ruby-on-rails rest token restful-authentication

我需要为Rails设计一个RESTful API,它将支持从网络浏览器,智能手机,平板电脑等登录。当我登录时,它总是需要X-CSRF-Token,所以每次我需要使用会话或cookie信息。但是,REST api应该是无状态的,这意味着不应该使用cookie。有没有办法摆脱它?有什么建议吗?

1 个答案:

答案 0 :(得分:1)

以下是我在应用HTML和JSON的应用中处理此问题的方法。我想要CSRF检查,除非它是来自可靠来源的API调用,所以

application_controller.rb

class ApplicationController < ActionController::Base
  protect_from_forgery
  # has to come after the protect_from_forgery line
  skip_before_filter :verify_authenticity_token, :if => :api_request?

  # but don't just accept any URL with a .json extension, you need something else to
  # ensure your caller is trusted (in this case I test for a valid API key being passed)
  before_filter :api_key_valid?, :if => :api_request?

  def api_request?
    request.format == 'application/json'
  end

  # ... etc
end