加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 会话存储在Rails中的哪个位置?

发布时间:2020-12-16 23:24:53 所属栏目:百科 来源:网络整理
导读:在Rails中,我已经为用户身份验证实现了以下代码(确认是正确的).但是,我想确认我对这个奇怪会话的想法[:session_token].这是存储在浏览器中的“cookie”吗? class ApplicationController ActionController::Base protect_from_forgery with: :exception hel
在Rails中,我已经为用户身份验证实现了以下代码(确认是正确的).但是,我想确认我对这个奇怪会话的想法[:session_token].这是存储在浏览器中的“cookie”吗?
class ApplicationController < ActionController::Base
  protect_from_forgery with: :exception

  helper_method :current_user,:signed_in?

  private
  def current_user
    @current_user ||= User.find_by_session_token(session[:session_token])
  end

  def signed_in?
    !!current_user
  end

  def sign_in(user)
    @current_user = user
    session[:session_token] = user.reset_token!
  end

  def sign_out
    current_user.try(:reset_token!)
    session[:session_token] = nil
  end

  def require_signed_in!
    redirect_to new_session_url unless signed_in?
  end
end

到目前为止,我对其工作原理的理解是,每当浏览器/客户端向rails发送请求时,cookie(带有会话[:session_token])也会被发送,从而允许current_user方法查找用户.我的理解是否正确?这对我来说很奇怪,因为当我们在ApplicationController(Rails-side)中声明它时,浏览器/客户端访问会话cookie的确切方式存在差距.

解决方法

你几乎就在那里.虽然,我有一种感觉,你可能会混淆苹果和橘子……

会议:

通常在动态网站中,人们会希望在HTTP请求之间存储用户数据(因为http是无状态的,否则你无法将请求与任何其他请求相关联),但是你不希望这些数据是可读的和/或可以在URL的客户端内部编辑(例如.. yourwebsite.com/yourPage?cookie=12345u0026amp;id=678),等等…,因为您不希望客户端使用该数据没有通过您的服务器端代码.

解决这个问题的一种方法是存储数据服务器端,给它一个“session_token”(就像你所说的那样),让客户端只知道(并在每个http请求时传回)该令牌.这就是会话的实现方式.

饼干:

在Rails中实现会话的最常用技术涉及使用cookie,这些cookie是放置在用户浏览器上的小块文本.由于cookie从一个页面持续存储到下一个页面,因此它们可以存储可由应用程序用于从数据库中检索登录用户的信息(例如session_token或您想要的任何其他内容).

Where is the Session Stored in Rails?

使用上述两个概念,我现在可以告诉你Rails中的默认会话存储是CookieStore,大小约为4KB.

简而言之…

def sign_in(user)
  @current_user = user
  session[:session_token] = user.reset_token!
end

…您定义的方法将用户置于临时会话中.

然后想法是以下……

def current_user
  @current_user ||= User.find_by_session_token(session[:session_token])
end

…方法将从对应于会话令牌的数据库中查找并检索用户,并将其初始化为您指定的变量.

附加信息:

您还应该注意到Rails的会话和cookie帮助方法之间存在重要区别……

它们都生成cookie,但是,session […]方法会生成临时cookie,这些cookie应该在浏览器退出时到期,而cookies […]方法会创建持久性cookie,而不是.

另外,我建议你看看Ruby on Rails Security guide的第2部分.你可能会发现它很有用.

希望这可以帮助你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读