rails 报错Can't verify CSRF token authenticity的解决办法

本文详细介绍了在Rails应用中遇到的CSRF验证问题,并提供了一种替代解决方案,即关闭verify_authenticity_token验证并采用自定义加密方式实现用户身份验证。通过在控制器中使用skip_before_filter和AES加密解密方法,实现在POST请求时验证用户身份,确保应用安全性和用户体验。同时,文章还分享了解决方案的稳定性问题和实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决:在controller下面加上
skip_before_filter :verify_authenticity_token, :only => [:create]
class PostsController < ApplicationController

   skip_before_filter :verify_authenticity_token, :only => [:create]
   def create
        #your method
   end
end

这个问题是由于 Flash 的请求,Rails 无法获取 Session ,也就无法得到 CSRF ,也就是说连 current_user 也是无法获取到的,网上有很多教程是用 FlashSessionCookieMiddleware 这个方式来做,但实际用起来却没有那么稳定。 解决办法其实简单点可以关掉 verify_authenticity_token,然后用自定义加密的 current_user.id 方式代替,提交的时候将加密过的 current_user.id 提交回来解密就能得到当前用户的编号了。

class AttachmentsController < ApplicationController
  skip_before_filter :verify_authenticity_token, :only => [:create]

  def new
    @user_id = AES.encrypt(current_user.id.to_s, "自定义密钥")
  end

  def create
    @user_id = AES.decrypt(params[:uid], "自定义密钥")
    @attachment = Attachment.new(params[:attachment])
    @attachment.user_id = @user_id
    @attachment.save
  end
end 

不稳定的话可以用下面方法解决,就是把session加载进来

 prepend_before_filter :load_session, only: :flash_upload

 def load_session
    unless session.loaded?
      se = Marshal.load(ActiveSupport::Base64.decode64(params["_dituhui_session"]))
      logger.info("\n--------session is: #{se.inspect}-----------\n")
      request.session.update(se)
    end
  end

其实就是在authenticate_user!前,执行load_session


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值