request_forgery_protection.rb 4.5 KB
Newer Older
J
Jeremy Kemper 已提交
1 2
require 'active_support/core_ext/class/attribute'

3
module ActionController #:nodoc:
4 5
  class InvalidAuthenticityToken < ActionControllerError #:nodoc:
  end
6

7 8 9 10 11 12 13 14 15 16 17 18 19
  # Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks
  # by including a token in the rendered html for your application. This token is
  # stored as a random string in the session, to which an attacker does not have
  # access. When a request reaches your application, \Rails then verifies the received
  # token with the token in the session. Only HTML and javascript requests are checked,
  # so this will not protect your XML API (presumably you'll have a different
  # authentication scheme there anyway). Also, GET requests are not protected as these
  # should be idempotent.
  #
  # CSRF protection is turned on with the <tt>protect_from_forgery</tt> method,
  # which will check the token and raise an ActionController::InvalidAuthenticityToken
  # if it doesn't match what was expected. A call to this method is generated for new
  # \Rails applications by default. You can customize the error message by editing
20
  # public/422.html.
21 22 23
  #
  # The token parameter is named <tt>authenticity_token</tt> by default. The name and
  # value of this token must be added to every layout that renders forms by including
24
  # <tt>csrf_meta_tags</tt> in the html +head+.
25 26 27
  #
  # Learn more about CSRF attacks and securing your application in the
  # {Ruby on Rails Security Guide}[http://guides.rubyonrails.org/security.html].
28
  module RequestForgeryProtection
29
    extend ActiveSupport::Concern
30

31
    include AbstractController::Helpers
32
    include AbstractController::Callbacks
33 34

    included do
35 36
      # Sets the token parameter name for RequestForgery. Calling +protect_from_forgery+
      # sets it to <tt>:authenticity_token</tt> by default.
37 38
      config_accessor :request_forgery_protection_token
      self.request_forgery_protection_token ||= :authenticity_token
39

40
      # Controls whether request forgery protection is turned on or not. Turned off by default only in test mode.
41 42
      config_accessor :allow_forgery_protection
      self.allow_forgery_protection = true if allow_forgery_protection.nil?
43 44 45

      helper_method :form_authenticity_token
      helper_method :protect_against_forgery?
46
    end
47

48
    module ClassMethods
49
      # Turn on request forgery protection. Bear in mind that only non-GET, HTML/JavaScript requests are checked.
50
      #
D
David Heinemeier Hansson 已提交
51 52 53 54 55
      # Example:
      #
      #   class FooController < ApplicationController
      #     protect_from_forgery :except => :index
      #
56 57 58 59 60 61 62
      # You can disable csrf protection on controller-by-controller basis:
      #
      #   skip_before_filter :verify_authenticity_token
      #
      # It can also be disabled for specific controller actions:
      #
      #   skip_before_filter :verify_authenticity_token, :except => [:create]
D
David Heinemeier Hansson 已提交
63 64 65
      #
      # Valid Options:
      #
P
Pratik Naik 已提交
66
      # * <tt>:only/:except</tt> - Passed to the <tt>before_filter</tt> call.  Set which actions are verified.
67 68
      def protect_from_forgery(options = {})
        self.request_forgery_protection_token ||= :authenticity_token
Y
Yehuda Katz 已提交
69
        before_filter :verify_authenticity_token, options
70 71 72 73
      end
    end

    protected
74 75 76 77 78 79

      def protect_from_forgery(options = {})
        self.request_forgery_protection_token ||= :authenticity_token
        before_filter :verify_authenticity_token, options
      end

80
      # The actual before_filter that is used.  Modify this to change how you handle unverified requests.
81
      def verify_authenticity_token
82
        verified_request? || raise(ActionController::InvalidAuthenticityToken)
83
      end
Y
Yehuda Katz 已提交
84

85 86
      # Returns true or false if a request is verified.  Checks:
      #
87
      # * is the format restricted?  By default, only HTML requests are checked.
88
      # * is it a GET request?  Gets should be safe and idempotent
89
      # * Does the form_authenticity_token match the given token value from the params?
90
      def verified_request?
91
        !protect_against_forgery? || request.forgery_whitelisted? ||
92
          form_authenticity_token == params[request_forgery_protection_token]
93
      end
Y
Yehuda Katz 已提交
94

P
Pratik Naik 已提交
95
      # Sets the token value for the current session.
96
      def form_authenticity_token
97
        session[:_csrf_token] ||= ActiveSupport::SecureRandom.base64(32)
98
      end
99

100 101 102 103 104
      # The form's authenticity parameter. Override to provide your own.
      def form_authenticity_param
        params[request_forgery_protection_token]
      end

105
      def protect_against_forgery?
106
        allow_forgery_protection
107
      end
108
  end
109
end