开发者

How to use cookies in a Rack middleware?

开发者 https://www.devze.com 2023-02-18 00:07 出处:网络
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 be

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

开发者_如何学Python
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]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号