Skip to content

Instantly share code, notes, and snippets.

@killthekitten
Last active October 6, 2021 17:12
Show Gist options
  • Save killthekitten/b9a7b11530c44e788a31ec53e5ef0dad to your computer and use it in GitHub Desktop.
Save killthekitten/b9a7b11530c44e788a31ec53e5ef0dad to your computer and use it in GitHub Desktop.
Persistent CSRF token cookie
@rshipp
Copy link

rshipp commented Oct 6, 2021

thanks for this! for anyone else stumbling across it, a small change:

     def real_csrf_token(session)
       csrf_token = cookies.encrypted[COOKIE_NAME] || session[:_csrf_token]
-      csrf_token ||= SecureRandom.base64(AUTHENTICITY_TOKEN_LENGTH)
+      csrf_token ||= generate_csrf_token
       cookies.encrypted[COOKIE_NAME] ||= {
         value: csrf_token,
         expires: 1.year.from_now,
         httponly: true
       }
       session[:_csrf_token] = csrf_token
-      Base64.strict_decode64(csrf_token)
+      decode_csrf_token(csrf_token)

allows it to work (tested with Rails 6) when urlsafe_csrf_tokens are enabled, instead of raising an ArgumentError with invalid base64 if your existing token happens to contain the urlsafe-base64 underscore _ or dash - characters.

@killthekitten
Copy link
Author

@rshipp thanks for this! Did this workaround resolve your issue with CSRF though?

@rshipp
Copy link

rshipp commented Oct 6, 2021

It did! We just got the invalid base64 crash until we also fixed the urlsafe issue. Now our forms are all working perfectly across rails server restarts, which was failing without this csrf cookie fix.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment