2016-08-10 71 views
8

在同一頁面中的導軌4的應用程序上我在頭一個Rails的authenticity_token形式VS CSRF令牌

<meta name="csrf-param" content="authenticity_token" /> 
<meta name="csrf-token" content="some_token" /> 

及以下正文:

<form action="/someaction" method="post"> 
<input name="utf8" type="hidden" value="&#x2713;" /> 
<input type="hidden" name="_method" value="patch" /> 
<input type="hidden" name="authenticity_token" value="another_token" /> 

js調用需要csrf標記。但爲什麼表單標記與csrf標記不同?在表單提交中使用哪兩個令牌?

回答

0

我做了一些研究來回答你的問題,這裏是結果。

首先,讓我們來看看這部分:由方法csrf_meta_tags產生

<meta name="csrf-param" content="authenticity_token" /> 
<meta name="csrf-token" content="some_token" /> 

這部分。從源代碼中我們可以看到:

  1. 「內容」的<meta name="csrf-param" />屬性值從request_forgery_protection_token採取,並且在默認情況下,是:authenticity_token

  2. <meta name="csrf-token" />的「content」屬性值取自form_authenticity_token方法,其中令牌從會話中獲取或生成。

現在讓我們來看看這個部分:

<input type="hidden" name="authenticity_token" value="another_token" /> 

從源頭上,我們可以看到:

  1. 這個隱藏輸入由extra_tags_for_form方法返回。
  2. Inside extra_tags_for_form調用token_tag方法。
  3. token_tag方法將令牌作爲參數。
  4. tokentoken_tag的參數是事先從options自變量中提取的form_tag方法的html_options_for_form方法。

所以,如果你沒有手動設置authenticity_token PARAM在options到自定義的令牌,並沒有滿足,導致token值設置爲false(下文會提到)的條件下,token_tag方法將得到nil和調用用於<meta name="csrf-token" />標籤創建的相同方法form_authenticity_token。順便說一下,爲了填充name輸入的屬性,它也使用request_forgery_protection_token,這是在<meta name="csrf-param" />標籤生成發生時使用的。

而且因爲這一切都發生在同一個請求中,所以在兩種情況下調用form_authenticity_token方法都應返回相同的結果。

這兩個標記中的哪一個用於表單提交?

表單提交將使用來自隱藏輸入的令牌。

<meta />也令牌可以使用,但前提是所有的下面conditions(使token_tag方法token參數被設置爲false)將得到滿足:

  1. :remote => true應在form_tagoptions傳遞。
  2. embed_authenticity_token_in_remote_forms config設置爲false。
  3. authenticity_token沒有通過options

但爲什麼表單標記與csrf標記不同?

至於這個問題,也許這個問題是由於緩存發生的。或者,如果您使用Turbolinks gem,可能會導致此問題(如果您完全刷新頁面並再次比較令牌,則可以檢查此問題)。有關Turbolinks問題的更多信息,請查詢this question

+0

謝謝。我需要一些時間來看答案並理解它。 – thebravoman

+0

@thebravoman它對您有幫助嗎? –

+0

就是這樣,我只需要用我的應用程序測試幾件事就可以完全理解它 – thebravoman