ruby-on-rails-3 – Paperclip宝石触发CSRF令牌验证问题

前端之家收集整理的这篇文章主要介绍了ruby-on-rails-3 – Paperclip宝石触发CSRF令牌验证问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个使用回形针宝石(3.4版)的Rails 3.1应用程序.简而言之.我有一个故事模型和一个后期模型.一个故事可以有很多帖子.
  1. #story.rb
  2.  
  3. class Story < ActiveRecord::Base
  4.  
  5. attr_accessible :title,:user_id,:username,:posts_attributes
  6.  
  7. belongs_to :user
  8. has_many :posts,:dependent => :destroy,:order => "created_at DESC"
  9.  
  10. accepts_nested_attributes_for :posts,:reject_if => lambda { |t| t['contents'].nil? }
  11.  
  12. end
  1. #post.rb
  2.  
  3. class Post < ActiveRecord::Base
  4.  
  5. attr_accessible :contents,:photo,:dimensions
  6.  
  7. belongs_to :story,:touch => true
  8. belongs_to :user,:touch => true
  9.  
  10. has_attached_file :photo,:styles => {
  11. :medium => { :geometry => "400x400>" },:thumb => { :geometry => "100x100>" },},:processors => [:thumbnail],:storage => :s3,:s3_credentials => "#{Rails.root.to_s}/config/s3.yml",:path => "/:style/:id/:filename"
  12.  
  13.  
  14. before_save :extract_dimensions
  15.  
  16. serialize :dimensions
  17.  
  18. validates :contents,:presence => true,:length => { :maximum => 399,:minimum => 5 }
  19. validates :user_id,:presence => true
  20.  
  21. 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"
  22.  
  23. end

如您所见,帖子可能附有照片附件.我使用回形针来管理这些附件.

生成使用javascript / jquery在客户端上动态发布这些帖子的表单.我的问题是这个. . .如果帖子不包含照片附件,一切都可以完美. IF,但是,如果POST有照片附件,我收到以下错误消息,该帖子不POST:

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

结果,我的会话数据被破坏,我甚至不能看到与Firebug的请求头. put请求根本不会出现在firebug中.

现在,毫不奇怪,我可以在PostController中解决以下问题:

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

但我不想放弃这种安全.我也尝试通过js / jquery将CSRF头添加到我的表单中:

  1. jQuery.ajaxSetup({
  2. beforeSend: function(xhr) {
  3. xhr.setRequestHeader('X-CSRF-Token',$('Meta[name="csrf-
  4. token"]').attr('content'));
  5. }
  6. });

但是这并不能解决问题,正如我上面所说的,我甚至看不到请求头数据来看头.

任何人都可以看出纸夹是否触发问题的原因?

解决方法

我知道,自从我第一次发布上述问题以来,已经有一段时间了,但是人们仍然在搜索中找到它,所以我以为我会用一个答案来更新.

上面讨论的问题与Paperclip无关.由于我使用的是remotipart.js来处理提交具有文件附件的表单,因此该表单正在提交而无需使用csrf令牌. Remotipart通过将表单数据复制到i框架中,使表单类似于ajax,从而在您的站点保持活动状态时提供正常的(即非ajax)提交.有关通过i-frame进行的ajax文件上传的更详细的描述,请参见this article.

在以前的remotipart版本中,csrf令牌未被复制到i-frame提交的表单中.支持远程的好人现在已经解决了这个缺点.你可以找到修复here

猜你在找的Ruby相关文章