chu*_*k w 11 csrf paperclip ruby-on-rails-3 ruby-on-rails-3.1
我有一个Rails 3.1应用程序,它使用了paperclip gem(v 3.4.0).简而言之.我有一个故事模型和一个帖子模型.一个故事可以有很多帖子.
#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
Run Code Online (Sandbox Code Playgroud)
#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
Run Code Online (Sandbox Code Playgroud)
如您所见,帖子可能有照片附件.我使用回形针来管理这些附件.
我使用javascript/jquery生成在客户端上动态POST这些帖子的表单.我的问题是这个...如果帖子不包含照片附件,一切都很完美.如果,但是,一个帖子有一个照片附件,我收到以下错误消息,该帖子没有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
Run Code Online (Sandbox Code Playgroud)
结果,我的会话数据被销毁,我甚至无法看到Firebug的请求标头.put请求根本没有出现在firebug中.
现在,毫不奇怪,我可以通过PostController中的以下内容解决这个问题:
skip_before_filter :verify_authenticity_token, :only => [:create]
Run Code Online (Sandbox Code Playgroud)
但我不想放弃这种安全感.我也尝试通过js/jquery将CSRF头添加到我的表单中:
jQuery.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-
token"]').attr('content'));
}
});
Run Code Online (Sandbox Code Playgroud)
但这并没有解决问题,正如我上面所说,我甚至看不到请求标头数据来查看标头.
任何人都可以提出回形针触发问题的原因吗?
我知道自从我第一次发布上述问题以来已经有一段时间了,但人们仍在搜索中找到它,所以我想我会用答案来更新内容。
我上面讨论的问题与回形针无关。该表单在没有 csrf 令牌的情况下提交,因为我使用 remotipart.js 来处理具有文件附件的表单的提交。Remotipart 通过将表单数据复制到 i 框架中来实现类似 ajax 的表单提交,然后在您的站点保持活动状态时进行正常(即非 ajax)提交。有关通过 i-frame 上传 ajax 文件的更详细说明,请参阅本文。
在以前版本的 remotipart 中,csrf 令牌不会复制到 i-frame 提交的表单中。支持 remotipart 的好心人现在已经修复了这个缺点。您可以在这里找到修复方法