如果每个客户端都经过身份验证,则可以禁用真实性令牌
仅当您使用除 http cookie 之外的其他身份验证机制时,这才是正确的。因为您提到了“session_id”,所以我认为情况并非如此。
使用标准的 rails session_id cookie,user_id 存储在会话中,并且此操作可由网络浏览器访问,它将受到 csrf 攻击。
api 的最佳策略是实现自定义身份验证机制,某种身份验证令牌,与每个 http 标头一起发送。
然后将 csrf 保护更改为 null_session,或者如果您不那么偏执,请完全为您的 api 请求禁用 csrf 保护,如此处所述
如果您仍然想为您的 api 坚持基于 cookie 的身份验证,您应该将带有第一个 GET 请求的 csrf 身份验证令牌设置为额外的 cookie。然后你读取这个 cookie 并将它的令牌作为“X-CSRF-Token”标头发送。Rails 将在protect_from_forgery 方法中检查此标头,并且由于3d 方无法读取cookie,攻击者将无法伪造此请求。
#application_controller.rb
protect_from_forgery with: :exception
after_action :set_csrf
def set_csrf
cookies['X-CSRF-Token'] = form_authenticity_token if protect_against_forgery?
end
# request session and x-csrf-toke
# the cookies will be stored into cookie.txt
curl -c cookie.txt http://example.com
#curl post command
curl -H "X-CSRF-Token: <token>" -b cookie.txt -d '{"item":{"title":"test"}}' "http://example.com/items.json"
见:verified_request? 方法来查看 rails 如何检查请求伪造。