NoDisplayName
NoDisplayName

Reputation: 15746

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\"" 

Upvotes: 0

Views: 1902

Answers (3)

NoDisplayName
NoDisplayName

Reputation: 15746

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

Upvotes: 1

shivam
shivam

Reputation: 16506

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"

Upvotes: 2

Rajarshi Das
Rajarshi Das

Reputation: 12330

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)

Upvotes: 1

Related Questions