Create token_authenticatable without session cookies

I am using Rails 3 and I have successfully created web api. Login headers are required for a bunch of controllers, so I decided to use Devise and token_authenticable. It works, but not in the way I expected: although I needed to provide an input token for each request, instead it looks like it is needed only once, and then the system creates a cookie in the response just like usual browser session. I want to get something like facebook graph api, where each request had to provide a session token to work.

Is there any flag that I can configure to tell Devise not to send session cookies if I use web api and send session cookies if I use a browser?

+4
source share
2 answers

I had the same problem.

In the session controller of my API there was a line:

warden.authenticate!(:scope => resource_name, :recall => "#{controller_path}#failure") 

He registered the user and created a session (which I did not notice at the beginning)

The solution is to use something similar to this (found in the blogpost ):

 @user=User.find_by_email(email.downcase) if @user.nil? render :status=>401, :json=>{:message=>"Invalid email or password."} return end # http://rdoc.info/github/plataformatec/devise/master/Devise/Models/TokenAuthenticatable @user.ensure_authentication_token! if not @user.valid_password?(password) logger.info("User #{email} failed signin, password \"#{password}\" is invalid") render :status=>401, :json=>{:message=>"Invalid email or password."} else render :status=>200, :json=>{:token=>@user.authentication_token} end 

Basically, the user is not registered, but the token is extracted. The rest of the application, except for logging out, worked fine.

+1
source

I used protect_from_forgery with: :null_session so that the session is ignored.

0
source

All Articles