user1170896
user1170896

Reputation: 739

Devise token_authenticatable without session cookies

I'm using Rails 3 and I've succesfully built a web api. For a bunch of controllers login is required so i decided to use Devise and token_authenticable. It IS working but not quite as I was expecting: I though I needed to supply my login token for each request instead it looks like it's only needed once and then the system creates a cookie in the response just like a normal browser session. I want achieve something like facebook graph api where each request needs to have submitted the session token in order to work.

Is there any flag that I can set to instruct Devise to not send session cookies if I'm using web api and send session cookies if I'm using the browser?

Upvotes: 4

Views: 2906

Answers (2)

shohey1226
shohey1226

Reputation: 770

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

Upvotes: 1

Česlovas Lopan
Česlovas Lopan

Reputation: 103

I had the same problem.

There was a line in Sessions controller of my API:

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

It was logging user in and creating a session (which I didn't notice at first)

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 not logging user in, but retrieving the token. Other parts of application except for logging out were working fine.

Upvotes: 1

Related Questions