我正在使用 Ruby on Rails 3,我想在 Rack 中间件中使用 cookies.signed
方法。我需要它,因为我想直接在中间件中对用户进行身份验证,而不是在 application_controller.rb
文件中使用 before_filter
。
例如,如果我以这种方式在 Controller 中使用该方法:
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 以便对其进行身份验证?
也许我必须包括\扩展,例如,ActionDispatch...如果是这样,怎么做?
最佳答案
看起来你应该能够做到这一点:
request = ActionDispatch::Request.new(env)
request.cookie_jar.signed[:user_id] #=> 1
可以查看.../action_dispatch/middleware/cookies.rb在 github 上阅读更多关于到底发生了什么的信息。
关于ruby-on-rails - 如何在 Rack 中间件中使用 cookie?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5343208/