【问题标题】:Rail 4 Devise nil current_user for POST, PUT, DELETE JSON requestsRail 4 为 POST、PUT、DELETE JSON 请求设计 nil current_user
【发布时间】:2014-04-28 13:39:40
【问题描述】:

下面是 ApplicationController 和 OrdersController 的代码。

当 POST 请求创建新订单时,我在 login_required 中得到 current_user nil 并让过滤器链停止。

********** Request Format: [application/json] - current_user:[] - user_signed_in: [false]
14:30:26 web.1  | Filter chain halted as :login_required rendered or redirected
14:30:26 web.1  | Completed 401 Unauthorized in 19ms (Views: 0.3ms)

使用设计 database_authentication。不想使用 token_authentication。 建议需要如何为 POST/PUT JSON 请求获取 current_user。

  • 红宝石:2.1.1
  • 导轨:4
  • 设计:3.2.4
  • 典狱长:1.2.3

应用控制器:

  class ApplicationController < ActionController::Base

  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery 
  # with: :null_session

  before_filter :configure_permitted_parameters, if: :devise_controller?

  def login_required
    logger.info("********** Request Format: [#{request.format}] - current_user:[#{current_user}] - user_signed_in: [#{user_signed_in?}]")
    if request.format == :html
      authenticate_user!
      return
    end

    unless current_user
      is_validated = false
      respond_to do |format|
        format.json { render :json => is_validated,
           :status => :unauthorized}
        format.protobuf { render :text => ProtoHelper.to_session_proto(is_validated),
           :status => :unauthorized}
      end
    end
  end
end

class OrdersController < ApplicationController
  before_filter :login_required

  # POST /orders.json
  # POST /orders.protobuf
  def create
  end
end

【问题讨论】:

    标签: json ruby-on-rails-4 devise mongoid


    【解决方案1】:

    发现问题出在用户登录后清除session[_csrf_token]。这使得rails protect_from_forgery调用在日志中抛出警告消息:“无法验证CSRF令牌”并且无法在会话中找到用户。

    解决方案:

    config/initializers/devise.rb:

    将配置变量:clean_up_csrf_token_on_authentication 设置为 false,默认情况下,devise 将此设置设置为 true。

    config.clean_up_csrf_token_on_authentication = false
    

    【讨论】:

      猜你喜欢
      • 2013-05-13
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-19
      相关资源
      最近更新 更多