Rails将auth_token呈现给API响应头

时间:2016-02-12 11:15:21

标签: ruby-on-rails json authentication

我有自定义JSON身份验证API(没有设计等)。如何将@user.authentication_token呈现为响应标头而不是主体?

sessions_controller.rb

中的

  def create

    if @user && @user.authenticate(params[:user][:password])
      @user.sign_in_count += 1
      @user.save!

      render  status: 200,
              json: { success: true,
                      info: "Logged in sucessfully.",
                      data: { auth_token: @user.authentication_token } }
    else
      render  status: :unprocessable_entity,
              json: { success: false,
                      info: "Login failed." }
    end
  end

2 个答案:

答案 0 :(得分:4)

尝试response.header [“auth_token”]

    def create

        if @user && @user.authenticate(params[:user][:password])
          @user.sign_in_count += 1
          @user.save!

          render  status: 200,
                  json: { success: true,
                          info: "Logged in sucessfully."}
                   response.headers["auth_token"] = @user.authentication_token

        else
          render  status: :unprocessable_entity,
                  json: { success: false,
                  info: "Login failed." }
    end
  end

答案 1 :(得分:3)

您的控制器操作中有一个headers对象。所以你可以做到以下几点:

headers['X-User-Token'] = @user.authentication_token