簡體   English   中英

在Rails中擺脫X-CSRF-Token

[英]Get rid of X-CSRF-Token in Rails

我需要設計一個用於Rails的RESTful API,它將啟用從Web瀏覽器,智能手機,平板電腦等的登錄。登錄時,它始終需要X-CSRF-Token,因此每次我都需要使用會話或cookie信息。 但是REST api應該是無狀態的,這意味着不應該使用cookie。 有辦法擺脫它嗎? 有什么建議嗎?

這是我在同時響應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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM