设计 Rails API

Devise Rails API

谁能给我解释一下这行代码?

skip_before_filter :verify_authenticity_token, :if => Proc.new { |c| c.request.format == 'application/json' }

我应该使用它吗?为什么,为什么不。谢谢。

verify_authenticity_token 是一个 before_action(在每个控制器操作之前调用的方法,称为before_filter 在 Rails 之前 4) Rails 用来防止 CSRF 攻击。 You can read more about how Rails does this here.

这行代码的意思是:"if this is a JSON request then skip the CSRF check for this controller".

这对于 JSON API 很有用,这些 API 需要提供给不在同一域中的远程站点,因此会导致 CSRF 检查失败。这是安全的,前提是您确保 。但是,如果您的控制器不会被外部 Web 应用程序使用(并且您只是在自己的网站上做 AJAX 事情)那么请不要关闭 verify_authenticity_token 检查。