下面是ApplicationController和OrdersController的代码。

当POST请求创建新订单时,我在login_required中获得了current_user nil,并且停止了Filter Chain。

********** 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)


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


红宝石:2.1.1
滑轨:4
设计:3.2.4
守望者:1.2.3


ApplicationController:

  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

最佳答案

发现问题在于用户登录后设计清除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

关于json - Rail 4将nil current_user设置为POST,PUT,DELETE JSON请求,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23342692/

10-12 12:33
查看更多