简体   繁体   English

Rails将auth_token呈现给API响应头

[英]Rails render auth_token to API response header

I have custom JSON authentication API (without devise, etc). 我有自定义JSON身份验证API(没有设计等)。 How do I render @user.authentication_token to response header instead of body? 如何将@user.authentication_token呈现给响应头而不是body?

in sessions_controller.rb 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

Try the response.header["auth_token"] 试试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

There is a headers object available in your controller action. 控制器操作中有一个headers对象。 So you can do the following: 所以你可以做到以下几点:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用devise auth_token的Rails API注销已登录的用户 - Rails API using devise auth_token logs out logged in user 即使提供了api_key,通过AJAX向rails应用程序发布JSON也会引发无效的auth_token错误 - POSTing JSON via AJAX to rails app throws invalid auth_token error, even if the api_key is supplied RestClient使用auth_token获取 - RestClient get with auth_token 设计-auth_token和current_user - Devise - auth_token and current_user 使用请求标头的auth_token而不是Rails 3 / devise的POST / PUT参数 - Using auth_token from request headers instead from POST/PUT parameters with Rails 3 / devise 将Devise与Ruby on Rails一起使用,如果用户使用无效的auth_token,如何将用户发送到sign_in路径? - Using Devise with Ruby on Rails, how can I send the user to sign_in path if they use an invalid auth_token? 通过Devise的iOS用户登录会话,但未保留Auth_token - iOS User Login Session via Devise but Auth_token not kept vimeo ruby​​ gem oAuth的auth_token示例? - vimeo ruby gem auth_token example for oAuth? 在以下情况下如何替换auth_token字段 - How the replacement of auth_token field is working in below scenario Rake Migration:如何为所有用户输入auth_token到迁移中 - Rake Migration: How to enter an auth_token into a migration for all users
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM