【问题标题】:Ruby on Rails, Angularjs: Session getting resetRuby on Rails,Angularjs:会话被重置
【发布时间】:2014-11-02 19:35:06
【问题描述】:

我在 api 控制器中更改 session 中的值,但它不会反映下次获取 session 中该变量的值时。这是 api 控制器...

module Api
    module V0
        class RecommendationsApiController < ApplicationController

           def x
              r1 = session[:last_id]
              r2 = some_function(r1)
              session[:last_id] = r2 
              #doesn't reflect in the session next time this same function is called, and the old value is shown
              #though checking the value of session at this point shows the right value been set in the @delegate part of the session

           end
        end
    end
end

这是session_store.rb

Application.config.session_store :cookie_store, key: '_session_name'

application_controller.rb

  protect_from_forgery

  after_filter :set_csrf_cookie_for_ng

  def set_csrf_cookie_for_ng
    cookies['XSRF-TOKEN'] = form_authenticity_token if protect_against_forgery?
  end

  protected

  def verified_request?
    super || form_authenticity_token == request.headers['X-XSRF-TOKEN']
  end

这是websiteApp.run 函数。

var csrf_token = $cookies['XSRF-TOKEN'];
$http.defaults.headers.common['X-XSRF-TOKEN'] = csrf_token;

我尝试在config 中设置令牌,但config 块没有$cookies。所以尝试在run中设置headers

请帮忙。

【问题讨论】:

  • 您是否查看过浏览器中的 cookie 以查看该值是否实际到达浏览器?这将告诉您问题是未设置 cookie,还是未读取 cookie。那里有关于如何解密会话 cookie 的帖子

标签: ruby-on-rails angularjs session cookiestore


【解决方案1】:

您是否为该操作关闭了 CSRF 验证?如果不是,那么可能发生的是 Rails 出于安全原因正在清除会话。您应该只针对特定操作停用它:

protect_from_forgery :except => :my_action

或者在这种情况下

protect_from_forgery :except => :x

【讨论】:

  • 我没有关闭它。我已将application_controller.rb 添加到问题中。还有什么问题?
  • 我会去掉应用程序控制器中的 after 过滤器(如果它对其目的没有用),并在 RecommendationsApiController 添加以下行:'skip_before_filter :verify_authenticity_token, :only => [: x]'
  • 删除after_filter 并在RecommendationApiController 中添加skip_before_filter 没有好处。虽然这就是我必须添加这些行的原因 stackoverflow.com/questions/7600347/….. 我还能做什么?
  • 你在使用 AngularJS(AngularJS 是否在发出 API 请求)?
  • 是的,我正在使用 angularjs 发出 api 请求。
猜你喜欢
  • 2011-08-11
  • 1970-01-01
  • 2012-12-05
  • 2011-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多