Ruby Tips 10: Using Devise Gem for API Token Authentication

Ok. If you have already read the Devise gem wiki, you wouldn’t be seeing this, if not here is the simple way to do it.

Go to devise.rb and set
[source language=”ruby”]
# If true, authentication through token does not store user in session and needs
# to be supplied on each request. Useful if you are using the token as API token.
config.stateless_token = true
Now, have a RESTFul method that would look like
[source language=”ruby”]
def get_authentication_token
user = User.find_by_email(params[:user][:email])
password = params[:user][:password]
if user && user.encrypted_password == BCrypt::Engine.hash_secret(password, user.encrypted_password)
status = true
## do something with user object
render_json(false, “Invalid login or password.”, 401)

Related Posts

Leave a comment