Posted 22 days ago. Visible to the public.

Rails: Verify the CSRF token

Rails uses a CSRF token in forms and AJAX requests to verify a user request. Internally it compares the injected CSRF token of the form data with the CSRF token in the encrypted user session. To prevent SSL BREACH attacks, the CSRF token from the form data is masked.

To better debug issues, when these tokens do not match, it is useful to unmask the CSRF token from the form data. Here is a method that works for Rails 5.2.

Copy
def decode_csrf_token(csrf_token) decoded_masked_token = Base64.strict_decode64(csrf_token) one_time_pad = decoded_masked_token[0...32] encrypted_csrf_token = decoded_masked_token[32..-1] encrypted_csrf_token_bytes = encrypted_csrf_token.bytes one_time_pad.each_byte.with_index { |c1, i| encrypted_csrf_token_bytes[i] ^= c1 } csrf_token = encrypted_csrf_token_bytes.pack("C*") Base64.strict_encode64(csrf_token) end

Example form:

Copy
<input type="hidden" name="authenticity_token" value="af3uqNHd1MDskKeJH7+AiV7o8gozjqCsu78rbndSG/TlE+KPrKe2l3pltzi4O0xtFnUX3cRfsB+MxfP4BXvT6Q==">

Example usage:

Copy
decode_csrf_token("af3uqNHd1MDskKeJH7+AiV7o8gozjqCsu78rbndSG/TlE+KPrKe2l3pltzi4O0xtFnUX3cRfsB+MxfP4BXvT6Q==") => jO4MJ316YleW9RCxp4TM5Eid5df30RCzN3rYlnIpyB0=

Rails will only accept this request if jO4MJ316YleW9RCxp4TM5Eid5df30RCzN3rYlnIpyB0= is the same as the value in your cookie:

Copy
{ "session_id"=>"8ef662867ab2457717ba74c143c08733", "timestamp"=>1572261371, "_csrf_token"=>"jO4MJ316YleW9RCxp4TM5Eid5df30RCzN3rYlnIpyB0=" }

Note: The session cookie is encrypted by default. You can decrypt it with Rails: Decrypt a session cookie.

By refactoring problematic code and creating automated tests, makandra can vastly improve the maintainability of your Rails application.

Owner of this card:

Avatar
Emanuel De
Last edit:
22 days ago
by Emanuel De
About this deck:
We are makandra and do test-driven, agile Ruby on Rails software development.
License for source code
Posted by Emanuel De to makandra dev
This website uses cookies to improve usability and analyze traffic.
Accept or learn more