Sinatra not persisting session with redirect on Ch

2019-03-25 15:04发布

Sinatra is not persisting my session with a redirect on Chrome. It is creating an entirely new session and i'm losing all my previous session data.

As an example (similar to the Sinatra docs), i'm doing something like this:

enable :sessions

get '/foo' do
  session[:user_id] = 123
  session[:session_id] # "ABC", for example

  redirect to('/bar')
end

get '/bar' do
  # this is "DEF" when responding to Chrome (wrong), 
  # but "ABC" when responding to Firefox or Safari (right)
  session[:session_id]

  # this is nil when responding to Chrome (wrong),
  # but 123 when responding to Firefox or Safari (right)
  session[:user_id]
end

I'm thinking this has something to do with how the different browsers respond to handling the session after a redirect response. Has anyone seen something similar to this, or have any ideas on how to resolve this while still using sessions?

Thanks in advance!

4条回答
疯言疯语
2楼-- · 2019-03-25 15:48

By doing enable :sessions you just get access to session per request. Sinatra has no way to keep the reference to the previous call (your redirect) as it is treated as another request.

Thus, long story short:

set :session_secret, "SecureRandom.new(10) generated thing" enable :sessions

always use enable :sessions with a secret, otherwise your session is recreated every time rack sees a request.

查看更多
放我归山
3楼-- · 2019-03-25 15:58

Add this to your main app file: use Rack::Session::Cookie, :key => 'rack.session', :path => '/', :secret => 'some-random-string'

With that added, you should be able to assign session['whatever'] and have it work as expected.

查看更多
Emotional °昔
4楼-- · 2019-03-25 16:00

Please try to disable all custom cookie managament extensions is Chrome if any. After that check headers in Developer toolsNetwork. Should see 'Cookie:' field.

查看更多
霸刀☆藐视天下
5楼-- · 2019-03-25 16:00

I think that just because you didn't set :session_secret, refer to my answer on here

查看更多
登录 后发表回答