Category Archives: 技巧

处理InvalidAuthenticityToken异常

Rails 2.3引入的防止跨站攻击的功能在某些情况下会导致用户正常使用时也产生InvalidAuthenticityToken异常,比如某个表单需要登录后才能提交,但是用户在登录后,过了很长一段时间才提交,此时Session已经失效,就会导致这个异常,有些人会直接忽略验证AuthenticityToken的filter,但是这样有安全隐患,比较好的处理方法就是在ApplicationController中增加一个全局Handler: class ApplicationController < ActionController::Base &nsp; rescue_from ActionController::InvalidAuthenticityToken, :with => :bad_token    def bad_token     flash[:notice] = “Your session has expired.”     respond_to do |accepts|       accepts.html do         store_location         redirect_to(:controller => ‘/sessions’, :action => ‘new’) and return false        end        accepts.js do         store_location         render :update do |page|           page.redirect_to(:controller => ‘/sessions’, :action => ‘new’) and return false         end       end     end   end [...]

Posted in 技巧 | Leave a comment