request_forgery_protection.rb 4.7 KB
Newer Older
J
Jeremy Kemper 已提交
1
require 'active_support/core_ext/class/attribute'
2
require 'action_controller/metal/exceptions'
J
Jeremy Kemper 已提交
3

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

8 9 10
  # 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
11 12
  # access. When a request reaches your application, \Rails verifies the received
  # token with the token in the session. Only HTML and JavaScript requests are checked,
13 14 15 16 17
  # 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,
18 19 20
  # which checks the token and resets the session 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 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:
      #
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
69
        prepend_before_filter :verify_authenticity_token, options
70 71 72 73
      end
    end

    protected
74
      # The actual before_filter that is used. Modify this to change how you handle unverified requests.
75
      def verify_authenticity_token
76
        unless verified_request?
77
          logger.warn "WARNING: Can't verify CSRF token authenticity" if logger
78 79
          handle_unverified_request
        end
80 81
      end

82
      # This is the method that defines the application behavior when a request is found to be unverified.
83
      # By default, \Rails resets the session when it finds an unverified request.
84 85
      def handle_unverified_request
        reset_session
86
      end
Y
Yehuda Katz 已提交
87

88
      # Returns true or false if a request is verified. Checks:
89 90
      #
      # * is it a GET request?  Gets should be safe and idempotent
91
      # * Does the form_authenticity_token match the given token value from the params?
92
      # * Does the X-CSRF-Token header match the form_authenticity_token
93
      def verified_request?
94 95 96
        !protect_against_forgery? || request.get? ||
          form_authenticity_token == params[request_forgery_protection_token] ||
          form_authenticity_token == request.headers['X-CSRF-Token']
97
      end
Y
Yehuda Katz 已提交
98

P
Pratik Naik 已提交
99
      # Sets the token value for the current session.
100
      def form_authenticity_token
101
        session[:_csrf_token] ||= SecureRandom.base64(32)
102
      end
103

104 105 106 107 108
      # The form's authenticity parameter. Override to provide your own.
      def form_authenticity_param
        params[request_forgery_protection_token]
      end

109
      def protect_against_forgery?
110
        allow_forgery_protection
111
      end
112
  end
113
end