Action Controller Request Forgery Protection¶↑
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 verifies the received token with the token in the session. All requests are checked except GET requests as these should be idempotent. Keep in mind that all session-oriented requests are CSRF protected by default, including JavaScript and HTML requests.
Since HTML and JavaScript requests are typically made from the browser, we need to ensure to verify request authenticity for the web browser. We can use session-oriented authentication for these types of requests, by using theprotect_from_forgery method in our controllers.
GET requests are not protected since they don’t have side effects like writing to the database and don’t leak sensitive information. JavaScript requests are an exception: a third-party site can use a <script> tag to reference a JavaScript URL on your site. When your JavaScript response loads on their site, it executes. With carefully crafted JavaScript on their end, sensitive data in your JavaScript response may be extracted. To prevent this, only XmlHttpRequest (known as XHR or Ajax) requests are allowed to make requests for JavaScript responses.
Subclasses ofActionController::Base are protected by default with the:exception strategy, which raises an ActionController::InvalidAuthenticityToken error on unverified requests.
APIs may want to disable this behavior since they are typically designed to be state-less: that is, the requestAPI client handles the session instead ofRails. One way to achieve this is to use the:null_session strategy instead, which allows unverified requests to be handled, but with an empty session:
classApplicationController<ActionController::Baseprotect_from_forgerywith::null_sessionend
Note thatAPI only applications don’t include this module or a session middleware by default, and so don’t require CSRF protection to be configured.
The token parameter is namedauthenticity_token by default. The name and value of this token must be added to every layout that renders forms by includingcsrf_meta_tags in the HTMLhead.
Learn more about CSRF attacks and securing your application in theRuby on Rails Security Guide.
- MODULEActionController::RequestForgeryProtection::ClassMethods
- MODULEActionController::RequestForgeryProtection::ProtectionMethods
- CLASSActionController::RequestForgeryProtection::CookieStore
- CLASSActionController::RequestForgeryProtection::SessionStore
- A
- C
- F
- G
- M
- N
- P
- R
- U
- V
- X
Constants
| AUTHENTICITY_TOKEN_LENGTH | = | 32 |
| CSRF_TOKEN | = | "action_controller.csrf_token" |
Class Public methods
new(...)Link
Instance Public methods
commit_csrf_token(request)Link
reset_csrf_token(request)Link
Instance Private methods
any_authenticity_token_valid?()Link
Checks if any of the authenticity tokens from the request are valid.
compare_with_global_token(token, session = nil)Link
compare_with_real_token(token, session = nil)Link
csrf_token_hmac(session, identifier)Link
form_authenticity_param()Link
The form’s authenticity parameter. Override to provide your own.
form_authenticity_token(form_options: {})Link
Creates the authenticity token for the current request.
global_csrf_token(session = nil)Link
mark_for_same_origin_verification!()Link
GET requests are checked for cross-origin JavaScript after rendering.
marked_for_same_origin_verification?()Link
If theverify_authenticity_token before_action ran, verify that JavaScript responses are only served to same-origin GET requests.
mask_token(raw_token)Link
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 546defmask_token(raw_token)# :doc:one_time_pad =SecureRandom.random_bytes(AUTHENTICITY_TOKEN_LENGTH)encrypted_csrf_token =xor_byte_strings(one_time_pad,raw_token)masked_token =one_time_pad+encrypted_csrf_tokenencode_csrf_token(masked_token)end
non_xhr_javascript_response?()Link
Check for cross-origin JavaScript responses.
per_form_csrf_token(session, action_path, method)Link
protect_against_forgery?()Link
Checks if the controller allows forgery protection.
real_csrf_token(_session = nil)Link
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 575defreal_csrf_token(_session =nil)# :doc:csrf_token =request.env.fetch(CSRF_TOKEN)dorequest.env[CSRF_TOKEN] =csrf_token_storage_strategy.fetch(request)||generate_csrf_tokenenddecode_csrf_token(csrf_token)end
request_authenticity_tokens()Link
Possible authenticity tokens sent in the request.
unmask_token(masked_token)Link
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 539defunmask_token(masked_token)# :doc:# Split the token into the one-time pad and the encrypted value and decrypt it.one_time_pad =masked_token[0...AUTHENTICITY_TOKEN_LENGTH]encrypted_csrf_token =masked_token[AUTHENTICITY_TOKEN_LENGTH..-1]xor_byte_strings(one_time_pad,encrypted_csrf_token)end
valid_authenticity_token?(session, encoded_masked_token)Link
Checks the client’s masked token to see if it matches the session token. Essentially the inverse ofmasked_authenticity_token.
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 509defvalid_authenticity_token?(session,encoded_masked_token)# :doc:if!encoded_masked_token.is_a?(String)||encoded_masked_token.empty?returnfalseendbeginmasked_token =decode_csrf_token(encoded_masked_token)rescueArgumentError# encoded_masked_token is invalid Base64returnfalseend# See if it's actually a masked token or not. In order to deploy this code, we# should be able to handle any unmasked tokens that we've issued without error.ifmasked_token.length==AUTHENTICITY_TOKEN_LENGTH# This is actually an unmasked token. This is expected if you have just upgraded# to masked tokens, but should stop happening shortly after installing this gem.compare_with_real_tokenmasked_tokenelsifmasked_token.length==AUTHENTICITY_TOKEN_LENGTH*2csrf_token =unmask_token(masked_token)compare_with_global_token(csrf_token)||compare_with_real_token(csrf_token)||valid_per_form_csrf_token?(csrf_token)elsefalse# Token is malformed.endend
valid_per_form_csrf_token?(token, session = nil)Link
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 561defvalid_per_form_csrf_token?(token,session =nil)# :doc:ifper_form_csrf_tokenscorrect_token =per_form_csrf_token(session,request.path.chomp("/"),request.request_method )ActiveSupport::SecurityUtils.fixed_length_secure_compare(token,correct_token)elsefalseendend
valid_request_origin?()Link
Checks if the request originated from the same origin by looking at the Origin header.
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 635defvalid_request_origin?# :doc:ifforgery_protection_origin_check# We accept blank origin headers because some user agents don't send it.raiseInvalidAuthenticityToken,NULL_ORIGIN_MESSAGEifrequest.origin=="null"request.origin.nil?||request.origin==request.base_urlelsetrueendend
verified_request?()Link
Returns true or false if a request is verified. Checks:
Is it a GET or HEAD request? GETs should be safe and idempotent
Does the
form_authenticity_tokenmatch the given token value from the params?Does the
X-CSRF-Tokenheader match theform_authenticity_token?
verify_authenticity_token()Link
The actual before_action that is used to verify the CSRF token. Don’t override this directly. Provide your own forgery protection strategy instead. If you override, you’ll disable same-origin<script> verification.
Lean on the protect_from_forgery declaration to mark which actions are due for same-origin request verification. If protect_from_forgery is enabled on an action, this before_action flags its after_action to verify that JavaScript responses are for XHR requests, ensuring they follow the browser’s same-origin policy.
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 398defverify_authenticity_token# :doc:mark_for_same_origin_verification!if!verified_request?logger.warnunverified_request_warning_messageiflogger&&log_warning_on_csrf_failurehandle_unverified_requestendend
verify_same_origin_request()Link
Ifverify_authenticity_token was run (indicating that we have forgery protection enabled for this request) then also verify that we aren’t serving an unauthorized cross-origin response.
# File actionpack/lib/action_controller/metal/request_forgery_protection.rb, line 436defverify_same_origin_request# :doc:ifmarked_for_same_origin_verification?&&non_xhr_javascript_response?iflogger&&log_warning_on_csrf_failurelogger.warnCROSS_ORIGIN_JAVASCRIPT_WARNINGendraiseActionController::InvalidCrossOriginRequest,CROSS_ORIGIN_JAVASCRIPT_WARNINGendend