2013-03-07 61 views
11

我有一個Rails 3.1應用程序,使用回形針寶石(v 3.4.0)。簡而言之。我有一個故事模型和一個後期模型。一個故事可以有很多帖子。回形針寶石觸發CSRF令牌驗證問題

#story.rb 

class Story < ActiveRecord::Base 

    attr_accessible :title, :user_id, :username, :posts_attributes 

    belongs_to :user 
    has_many  :posts, :dependent => :destroy, 
         :order => "created_at DESC" 

    accepts_nested_attributes_for :posts, :reject_if => lambda { |t| t['contents'].nil? } 

end 

#post.rb 

class Post < ActiveRecord::Base 

    attr_accessible :contents, :photo, :dimensions 

    belongs_to :story, :touch => true 
    belongs_to :user, :touch => true 

    has_attached_file :photo, 
        :styles => { 
         :medium => { :geometry => "400x400>" }, 
         :thumb => { :geometry => "100x100>" }, 
        }, 
        :processors => [:thumbnail], 
        :storage => :s3, 
        :s3_credentials => "#{Rails.root.to_s}/config/s3.yml", 
        :path => "/:style/:id/:filename" 


    before_save :extract_dimensions 

    serialize :dimensions 

    validates :contents, :presence => true, 
         :length   => { :maximum => 399, 
             :minimum => 5 } 
    validates :user_id, :presence => true 

    validates_attachment_content_type :photo, 
    :content_type => ['image/jpeg', 'image/png', 'image/gif', 'image/jpg'], 
    :message => "Sorry, we don't support that type of image format" 

end 

正如你所看到的信息可能有照片附件。我使用回形針來管理這些附件。

我使用javascript/jquery生成在客戶端動態發佈這些帖子的表單。我的問題是這樣的。 。 。如果該帖子不包含照片附件,那麼所有內容都可以正常工作但是,如果一個帖子有照片附件,我收到以下錯誤消息和帖子不POST:

WARNING: Can't verify CSRF token authenticity 
    User Load (0.5ms) SELECT "users".* FROM "users" WHERE "users"."id" = 61 LIMIT 1 
    (0.3ms) BEGIN 
    (0.2ms) COMMIT 
Completed 401 Unauthorized in 238ms 

其結果是,我的會話數據被破壞,我甚至不能看請求標題與螢火蟲。放入請求根本不會出現在螢火蟲中。

現在,這並不奇怪,我可以解決這個問題,在PostController中的以下內容:

skip_before_filter :verify_authenticity_token, :only => [:create] 

但我不想放棄這個安全性。我也試圖通過添加CSRF頭到我的形式JS/jQuery的:

jQuery.ajaxSetup({ 
    beforeSend: function(xhr) { 
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-   
      token"]').attr('content')); 
    } 
}); 

但是,這並不解決問題,正如我上面所說的,我甚至不能看到請求頭數據看標題。

任何人都可以提出一個爲什麼回形針觸發問題的原因嗎?

+4

同樣的問題在這裏 – Pasta 2013-04-14 21:37:00

回答

1

我知道它已經有一段時間,因爲我第一次公佈了上述問題,但人們仍在尋找它自己的搜索,所以我想我會更新事情的答案。

上面討論的問題與Paperclip無關。由於我使用remotipart.js來處理提交帶有文件附件的表單,所以表單沒有提供csrf標記。 Remotipart通過將表單數據複製到i-框架中,使您的網站保持活動狀態時進行正常(即非ajax)提交,從而實現類似於ajax的提交。請參閱this article瞭解通過i-frame上傳ajax文件的更詳細說明。

在以前版本的remotipart中,csrf標記未被複制到i幀提交的表單中。支持remotipart的好人現在已經解決了這個缺點。你可以找到修復here

0
$.ajaxSetup({ 
    beforeSend: function(xhr) { 
     xhr.setRequestHeader('X-CSRF-Token', 
          $('meta[name="csrf-token"]').attr('content')); 
    } 
}); 

在JS

,並在佈局

<%= csrf_meta_tags %> 

文件應該是足以令它的工作。

否則,你可以使用jquery-rails的寶石,處理CSRF令牌

+0

大多隻需<%= csrf_meta_tags%>在佈局 - 在節。 – Eskim0 2013-10-20 00:52:37