[英]How to use cookies in a Rack middleware?
我正在使用Ruby on Rails 3,我想在Rack中间件中使用cookies.signed
方法。 我需要这个,因为我想直接在中间件中验证用户,而不是在application_controller.rb
文件中使用before_filter
。
例如,如果我以这种方式在控制器中使用该方法:
cookies.signed[:user_id']
我明白了
---
- 1 # This is the id of the current signed in user
- a64ee3asdtjhcc7b35fcb280956be00ba27f94d48dfe4291c06db7d57577d5893 # This is the cookie salt
但如果我在这个方式的Rack中间件(同一个应用程序)中使用它:
request = Rack::Request.new(env)
request.cookies.signed[:user_id']
我明白了
NoMethodError
undefined method `signed' for #<Hash:0x00000103333d40>
那么, 我怎样才能在中间件中使用该方法呢? 如何获取用户ID以便我可以对其进行身份验证?
也许我必须包含\\ extend,例如,ActionDispatch ...如果是这样,怎么样?
看起来你应该能够做到这一点:
request = ActionDispatch::Request.new(env)
request.cookie_jar.signed[:user_id] #=> 1
您可以在github上查看... / action_dispatch / middleware / cookies.rb ,详细了解正在发生的事情。
env
哈希中存在已初始化的cookie jar。
env['action_dispatch.cookies'].signed[:user_id]
上面的示例等效于在ActionController::Base
实例上下文中调用以下内容:
cookies.signed[:user_id]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.