How to use cookies in a Rack middleware?

user502052 picture user502052 · Mar 17, 2011 · Viewed 7.8k times · Source

I am using Ruby on Rails 3 and I would like to use the cookies.signed method in a Rack middleware. I need that because I would like to authenticate a user directly in the middleware than of using a before_filter in the application_controller.rb file.

For example, if I use that method in a controller this way:

cookies.signed[:user_id']

I get

--- 
- 1 # This is the id of the current signed in user
- a64ee3asdtjhcc7b35fcb280956be00ba27f94d48dfe4291c06db7d57577d5893 # This is the cookie salt

but if I use that in a Rack middleware (of the same application) this way:

request = Rack::Request.new(env)
request.cookies.signed[:user_id']

I get

NoMethodError
undefined method `signed' for #<Hash:0x00000103333d40>

So, how can I make it possible to use that method in a middleware? How can I get the user id so that I can authenticate that?


Maybe I have to include\extend, for example, the ActionDispatch... if so, how?

Answer

eric picture eric · Mar 20, 2011

It looks like you should be able to do this:

  request = ActionDispatch::Request.new(env)
  request.cookie_jar.signed[:user_id] #=> 1

You can check out .../action_dispatch/middleware/cookies.rb on github to read more about exactly what is going on.