简体   繁体   中英

How to use cookies in a Rack middleware?

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?

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.

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]

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