简体   繁体   中英

Decode a signed cookie in rails?

So I have a signed cookie that has the following value

IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci--a3c3b748fd207ba1c537b590dd458b4855677146

I need to decode it and get the following value

5oTgH9miQN8BI94VYR_Tvw

I tried something like

Base64.decode64(cookie_value.split('--').first)

but it gives me the wrong value, it adds these damn slashes in the string so I end up with

"\"5oTgH9miQN8BI94VYR_Tvw\"" 

but it gives me the wrong value, it adds these damn slashes in the string so I end up with

"\\"5oTgH9miQN8BI94VYR_Tvw\\""

Its not adding any slashes. The issue here is your returned string is included between double quotes " . \\" here is escape character.

Here:

Base64.decode64 "IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci"
# => "\"5oTgH9miQN8BI94VYR_Tvw\""
puts Base64.decode64 "IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci"
# "5oTgH9miQN8BI94VYR_Tvw"

As the problem is unwanted " s. You can remove them as follows:

Base64.decode64(cookie_value.split('--').first).chomp('"').reverse.chomp('"').reverse
# => "5oTgH9miQN8BI94VYR_Tvw"

Please try this

require 'rack'

puts Rack::Session::Cookie::Base64::Marshal.new.decode("IjVvVGdIOW1pUU44Qkk5NFZZUl9Udnci")

Also you can decrypt it.

Marshal.load(ActiveSupport::Base64.decode64(the_cookie_value.split("--").first)

I ended up using the following:

MultiJson.load(Base64.decode64(cookie_value.split('--').first))

probably works only with rails 4.1 +, although I am not sure

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM