7

In devise, how do i access the authentication token of a user. When an ajax call initiates a user session, I need to able to get an authentication token out of the user. I've tried to do things like adding :token_authenticable in my model

devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

also adding attributes of names like :authentication_token, and :authenticity_token to attr_accessible. But every time i try to call authentication_token or this authenticity_token out of the user with user.auth ... i get errors like this

NoMethodError: undefined method `authentication_token' for #<User:0x000001016b1140>

Sorry, i need to get this token to send with my ajax calls, (the last project i worked on i had an incredibly BOOTLEG solution where devise was nearly torn out of the application, i just need this damn token)

jack
  • 454
  • 2
  • 8
  • 22
  • i had a similar problem, let me know if u find a solution, not good reading material available – Kevin Dec 14 '11 at 02:46
  • 1
    token_authenticatable has been depreciated as seen here: http://stackoverflow.com/questions/18931952/devise-token-authenticatable-deprecated-what-is-the-alternative – dane Apr 18 '16 at 19:46

1 Answers1

8

This is fixed by including the :token_authenticatable module into the devise user model:

devise :token_authenticatable, ...

Also the method is defined on the class itself, not an instance. Call it as User.authentication_token.

See here: https://github.com/plataformatec/devise/blob/master/lib/devise/models/token_authenticatable.rb#L61-63.

Rob
  • 7,028
  • 15
  • 63
  • 95
Ryan Bigg
  • 106,965
  • 23
  • 235
  • 261
  • nice, sorry if i sound a little slow, but to check who a particular user is, should i make an attribute named auth_token and say user.auth_token = User.authentication_token. Then use this to verify who a user actually is. because it seems like devise is already making that parameter be sent whenever i change a view, but i cant manually do it with an ajax call – jack Dec 14 '11 at 12:39
  • The method authentication_token exists on both the instance and the class. Use instance method user.reset_authentication_token! to set the token (basically does user.authentication_token = User.authentication_token), devise should handle the actual verification part: "mysite.com/user/1/edit?auth_token=#{user.authentication_token}" – Homan Nov 01 '12 at 16:50