簡體   English   中英

如何在Rack中間件中使用cookie?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM