2017-04-11 161 views
4

背景細節的ActionController :: InvalidAuthenticityToken Rails的5 /設計/審計/ PaperTrail寶石

我使用設計進行身份驗證登錄到一個Rails的5應用。

每當我捆綁要麼審計紙徑寶石,當我嘗試#創建一個新的會話(通過形式符號 - /用戶/ sign_in),我收到以下錯誤:

ActionController::InvalidAuthenticityToken 

環境細節

紅寶石2.3.1

寶石:

  • 導軌 5.0.2
  • 設計 => 4.2.1
  • paper_trail => 7.0.1

重現步驟:

  1. 創建的Rails 5應用
  2. 添加設計的寶石
  3. 添加審計或紙徑寶石
  4. 嘗試登錄
+1

您是否在application_controller中使用':exception'保護了'protect_from_forgery? – whodini9

+2

@ whodini9 - 賓果。這是錯誤的原因。我把它改爲: 'protect_from_forgery prepend:true' 然後事情很開心。謝謝您的幫助。 – aldefouw

回答

15

事實證明,設計文檔相當關於此錯誤顯露:

For Rails 5, note that protect_from_forgery is no longer prepended to the before_action chain, so if you have set authenticate_user before protect_from_forgery, your request will result in "Can't verify CSRF token authenticity." To resolve this, either change the order in which you call them, or use protect_from_forgery prepend: true.

該修復程序是從我的應用程序控制器中更改代碼:

protect_from_forgery with: :exception 

要這樣:

protect_from_forgery prepend: true 

這個問題並沒有顯現出來,直到我試圖將經過審計或紙徑寶石。

+0

爲我工作,奇怪的是,如果您仍然登錄,問題不會出現,所以它似乎是間歇性的。 – Steve

+1

@JohnLinux - 我經歷過同樣的事情。 雖然我不認爲這是間歇性的。我認爲當你登錄時Devise會通過不同的調用堆棧發送給你。 – aldefouw

+0

這給我造成了很多困惑和沮喪。多個其他帖子提到'移動'它,但非特定的前置。謝謝。 – DNorthrup

0

在我的項目中,我們有這個問題,我們不能覆蓋 protect_from_forgery。 建立的解決方案是指示審計和爲我工作的github。

把這個在Gemfile中:

gem "audited", github: "collectiveidea/audited" 
+1

這似乎不是OP問題的答案? – LethalProgrammer

+1

@LethalProgrammer,對不起,我不明白OP的問題。我的答案是沒有編輯_protect_from_forgery_,因爲我的項目使用before_action回調在會話創建之前驗證某些東西。對不起,如果我的答案不清楚。 – msfreire

+0

@msfreire - 如果你使用你發佈的github分支,你是否建議你可以在應用程序控制器中使用'protect_from_forgery::exception' ? – aldefouw

0

documentation提及。

對於Rails 5,請注意protect_from_forgery不再作爲before_action鏈的前綴,因此如果您在protect_from_forgery之前設置了authenticate_user,那麼您的請求將導致「無法驗證CSRF令牌的真實性」。要解決此問題,請更改您調用它們的順序,或者使用protect_from_forgery prepend:true。

我已經使用過這樣的東西,它適用於我。

class WelcomeController < ::Base 
    protect_from_forgery with: :exception 
    before_action :authenticate_model! 
end 
相關問題