Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass Authenticity token through http header

I have a rails application that uses a token to authenticate the user. Currently I am passing the token as params. I would like to change this. I believe it is possible to pass it through html header. I dont understand how to use authenticate_or_request_with_http_token do |token, options|. My rails app is actually a server for my iphone client. I things I dont understand are:

  1. I know options is nonce but how will that work out between my client and server?

  2. How do I actually use this in my server code.

  3. I can use authenticate_or_request_with_http_token do |token, options| to check for token in the the header but how do I insert it into the header once a session is created successfully.

Here is my server Sessions Controller:

def create
if @user && @user.authenticate(params[:password])
 # @token = @user.auth_token
 @user.auth_token = SecureRandom.hex 
 @user.save
    respond_to do |format|
        format.json {render :json => {:status => "200", :message => "Logged in successfully", :auth_token => @user.auth_token}}
    end
else
    respond_to do |format|
        format.json {render :json => {:status => "401", :message => "wrong credentials"}}
    end
end
  end

  def destroy
    if(@user)
      @user.auth_token = ""
      @user.save
      respond_to do |format|
         format.json {render :json => {:status => "200", :message => "logged out successfully"}}
      end
    else
      respond_to do |format|
         format.json {render :json => {:status => "401", :message => "No User"}}
      end
   end
  end

def user
  @user = User.find_by_auth_token(params[:auth_token])
end
like image 367
nupac Avatar asked Jun 13 '13 07:06

nupac


1 Answers

to set custom headers you use response.headers.

Something like

response.headers["X-AUTH-TOKEN"] = auth_token

should work.. to read the header you use

request.headers["X-AUTH-TOKEN"]

the X- in the naming is a good practice convention, all custom headers should have an X- in front.

like image 129
Orlando Avatar answered Sep 19 '22 03:09

Orlando