rails中使用url传递sessionid

Enabling url parameter based sessions in Ruby on Rails

Posted by Paul McMahon on 2010年4月9日

Out of the box, Ruby on Rails uses cookies to store a user's session ID. This is fine for most applications, but doesn't work if your application needs to support browsers that don't support cookies, such as some mobile browsers. Instead of putting the session ID in a cookie, it must be put in the URL. This increases the possibility of session fixation attacks, where one user can take over another's session, however if security isn't paramount, this is an acceptable trade off. See the Ruby on Rails Security Guide for more details on these kinds of attacks.

To enable parameter based sessions in Rails, there are a number of changes you need to make. First, in config/initializers/session_store.rb, change the default file from containing something like

ActionController::Base.session = {
  :key         => '_application_session',
  :secret      => 'secret'
}

to

ActionController::Base.session = {
  :key         => '_application_session',
  :secret      => 'secret',
  :cookie_only => false # allow session to be loaded from params
}

# Overwrite default cookie based store
ActionController::Base.session_store = :active_record_store

Now Rails can read the session ID from the URL parameters, and doesn't store the session in a cookie (the default behaviour). Besides the ActiveRecord session store, other server based stores, such as the memcache store, work as well.

In addition to enabling Rails to read the session ID from the URL parameters, the session ID must be added as a parameter. The most basic way of doing this is to define default_url_options in the ApplicationController:

def default_url_options(options = nil)
  { request.session_options[:key] => request.session_options[:id] }
end

This will ensure that the session ID is always set in the URL.

The session ID can also be added conditionally, by doing something like the following:

def default_url_options(options = nil)
  if cookies_supported?
    super
  else
    { request.session_options[:key] => request.session_options[:id] }
  end
end

If the session ID is not included in the parameters, it will fall back to the cookie.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值