Pass authentication token through HTTP header

I have a rails application that uses a token to authenticate a user. I am currently passing a token as parameters. I would like to change that. I believe this can be passed through the html header. I do not understand how to use authenticate_or_request_with_http_token do |token, options| . The rails app is actually the server for my iphone client. I dont understand what:

  • I know options is nonce, but how will it work between my client and server?

  • How can I use this in my server code.

  • I can use authenticate_or_request_with_http_token do |token, options| to check the token in the header, but how to insert it in the header after a successful session creation.

Here is my server session 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 
+4
source share
1 answer

to set custom headers that you use response.headers .

Sort of

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

should work .. to read the header you are using

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

X- in the title is an agreement on good practice, all user headers should have X- in front of them.

+4
source

Source: https://habr.com/ru/post/1485944/


All Articles