From 1f9f102831d85004511ca85273fafde5ebf1c27b Mon Sep 17 00:00:00 2001 From: jbranchaud Date: Tue, 8 Dec 2020 00:32:06 -0600 Subject: [PATCH] Add Verify And Read A Signed Cookie Value as a rails til --- README.md | 3 +- .../verify-and-read-a-signed-cookie-value.md | 40 +++++++++++++++++++ 2 files changed, 42 insertions(+), 1 deletion(-) create mode 100644 rails/verify-and-read-a-signed-cookie-value.md diff --git a/README.md b/README.md index 4875e6d..23ead90 100644 --- a/README.md +++ b/README.md @@ -9,7 +9,7 @@ and pairing with smart people at Hashrocket. For a steady stream of TILs, [sign up for my newsletter](https://tinyletter.com/jbranchaud). -_971 TILs and counting..._ +_972 TILs and counting..._ --- @@ -645,6 +645,7 @@ _971 TILs and counting..._ - [Truncate Almost All Tables](rails/truncate-almost-all-tables.md) - [Update Column Versus Update Attribute](rails/update-column-versus-update-attribute.md) - [Upgrading Your Manifest For Sprocket's 4](rails/upgrading-your-manifest-for-sprockets-4.md) +- [Verify And Read A Signed Cookie Value](rails/verify-and-read-a-signed-cookie-value.md) - [Where Am I In The Partial Iteration?](rails/where-am-i-in-the-partial-iteration.md) - [Wipe Out All Precompiled Assets](rails/wipe-out-all-precompiled-assets.md) - [Write Reversible Migration To Set Default](rails/write-reversible-migration-to-set-default.md) diff --git a/rails/verify-and-read-a-signed-cookie-value.md b/rails/verify-and-read-a-signed-cookie-value.md new file mode 100644 index 0000000..8a5e0a8 --- /dev/null +++ b/rails/verify-and-read-a-signed-cookie-value.md @@ -0,0 +1,40 @@ +# Verify And Read A Signed Cookie Value + +Let's say a value was added as a [signed +cookie](https://apidock.com/rails/ActionDispatch/Cookies/CookieJar/signed) in a +request: + +```ruby +cookies.signed[:discount] = 45 +#=> Set-Cookie: discount=BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7; path=/ +``` + +Generally to verify and read that value, you'd grab it from the signed cookies +included in the request. + +```ruby +cookies.signed[:discount] +#=> 45 +``` + +What if you have the signed cookie value, but not in the context of a `cookies` +object? + +You can build a cookie jar from the current request and read the verified value +from that. + +```ruby +cookie_value = 'BAhpMg==--2c1c6906c90a3bc4fd54a51ffb41dffa4bf6b5f7' +cookie_hash = { discount: cookie_value } + +cookie_jar = ActionDispatch::Cookies::CookieJar.build(request, cookie_hash) + +cookie_jar.signed[:discount] +#=> 45 +``` + +It is also possible to [Base64 decode the +value](https://blog.bigbinary.com/2013/03/19/cookies-on-rails.html), however +that doesn't ensure that the value hasn't been tampered with. + +[source](https://philna.sh/blog/2020/01/15/test-signed-cookies-in-rails/)