2

I have custom JSON authentication API (without devise, etc). How do I render @user.authentication_token to response header instead of body?

in 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 Answers 2

4

Try the 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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, it works only without comma after json block
4

There is a headers object available in your controller action. So you can do the following:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.