【问题标题】:How do I ignore the authenticity token for specific actions in Rails?如何忽略 Rails 中特定操作的真实性令牌?
【发布时间】:2009-07-24 13:58:23
【问题描述】:

当我不想检查真实性令牌的特定操作时,如何让 Rails 跳过检查它?

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    Rails 5.2+

    您可以使用下面列出的相同skip_before_action 方法或新方法skip_forgery_protection,它是skip_before_action :verify_authenticity_token 的精简包装器

    skip_forgery_protection
    

    Rails 4+:

    # entire controller
    skip_before_action :verify_authenticity_token
    
    # all actions except for :create, :update, :destroy
    skip_before_action :verify_authenticity_token, except: [:create, :destroy]
    
    # only specified actions - :create, :update, :destroy
    skip_before_action :verify_authenticity_token, only: [:create, :destroy]
    

    See all options @ api.rubyonrails.org


    Rails 3 及以下:

    skip_before_filter :verify_authenticity_token
    

    【讨论】:

    • 对于特定控制器和特定操作,使用:skip_before_filter :verify_authenticity_token, :only=> :my_unprotected_action。我来这里是为了找到答案:这是一个糟糕的主意吗?我希望这样做,因为 ajax 响应会占用我的会话。
    • 对于 rails 5.2,使用 skip_forgery_protection。见API docs
    【解决方案2】:

    Rails4 中,您使用 skip_before_actionexceptonly

    class UsersController < ApplicationController
      skip_before_action :verify_authenticity_token, only: [:create]
      skip_before_action :some_custom_action, except: [:new]
    
      def new
        # code
      end
    
      def create
        # code
      end
    
      protected
      def some_custom_action
        # code
      end
    end
    

    【讨论】:

    • 谢谢。它帮助我为类似的问题创建了this answer。 :)
    猜你喜欢
    • 2011-05-05
    • 1970-01-01
    • 2011-03-04
    • 2013-04-21
    • 2013-07-22
    • 2010-09-15
    • 2018-06-29
    • 1970-01-01
    • 2021-12-10
    相关资源
    最近更新 更多