【问题标题】:Rails render auth_token to API response headerRails 将 auth_token 渲染到 API 响应标头
【发布时间】:2016-02-12 11:15:20
【问题描述】:

我有自定义 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

【问题讨论】:

    标签: ruby-on-rails json authentication


    【解决方案1】:

    试试 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
    

    【讨论】:

    • 谢谢,json块后不带逗号才有效
    【解决方案2】:

    您的控制器操作中有一个headers 对象可用。因此,您可以执行以下操作:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-23
      • 1970-01-01
      • 2012-12-28
      • 2023-03-29
      • 2011-10-03
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多