15

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?

user502052
  • 14,803
  • 30
  • 109
  • 188

2 Answers2

22

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.

eric
  • 1,168
  • 8
  • 18
  • 1
    This pointed me in the right direction but still raised the same error (using Rails 4.2.7). The issue was the missing application secrets in the `env`. Replacing the first line with the following worked: `ActionDispatch::Request.new(Rails.application.env_config.merge(env))`. – jeffcarbs Jan 23 '17 at 16:21
  • ActionDispatch is a good answer for rails. However the question asks for a Rack middleware solution. – Zach Aug 29 '22 at 20:40
6

A already initialized cookie jar is present in the env hash.

env['action_dispatch.cookies'].signed[:user_id]

The example above is equivalent to call the below in a ActionController::Base instance context:

cookies.signed[:user_id]
  • 5
    Unfortunately the `env['action_dispatch.cookies']` isn't available for any rack apps. It's only set very late in the request processing. – Dmytrii Nagirniak Jul 18 '14 at 07:20