Ruby Tips 10: Using Devise Gem for API Token Authentication

Surendran Sukumaran

27 sec read

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
[/source]
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
else
render_json(false, “Invalid login or password.”, 401)
end
end
[/source]

Related posts:

Leave a Reply

Your email address will not be published. Required fields are marked *