refaelos
refaelos

Reputation: 8075

set timeout for a token in rails

How do i set a timeout for a given authentication token? After the timeout, the token will be deleted and the user won't be able to use it on his requests.

I'm using rails 3 and devise.

Upvotes: 3

Views: 10215

Answers (3)

frankmt
frankmt

Reputation: 133

I'm not sure if that's exactly what you are looking for, but this is a simple option in Devise. If you set the following option in config/initializers/devise.rb

config.timeout_in = 30.minutes

then Devise will expire the token after 30 minutes of inactivity. The same operations that Devise does for session authentication should also work with the authentication_token.

I have used that in my current project and tested it using Timecop gem:

it "should timeout without activity after 30 minutes" do
    auth_token = @user.authentication_token

    get "/frontend/users/#{@user.id}.json?auth_token=#{auth_token}"
    response.status.should == 200

    Timecop.travel(45.minutes.from_now)
    get "/frontend/users/#{@user.id}.json?auth_token=#{auth_token}"
    response.status.should == 401 

    Timecop.return
end

Also, I don't believe that the token follows the same analogy as user/password combination as mentioned in one of the comments, since you wouldn't store your password in plain text but you do with your token. I would recommend resetting the token after each logout as well.

Upvotes: 2

Ricardo
Ricardo

Reputation: 697

At devise initializer file

#/config/initializers/devise.rb

# ==> Configuration for :timeoutable
# The time you want to timeout the user session without activity. After this
# time the user will be asked for credentials again. Default is 30 minutes.
config.timeout_in = 1.day

# If true, expires auth token on session timeout.
config.expire_auth_token_on_timeout = true

Upvotes: 1

kambi
kambi

Reputation: 3433

I was looking for this feature too, but didn't find a way to do it directly.

You can reset the authentication token on each sign-in and use the rememberable in-between:

in your application controller, in after_sign_in_path_for():

resource.reset_authentication_token

in devise.rb:

config.remember_for = 1.day

Or you can create a cron-job to periodically clear the invalid authentication_token entries from the users table.

Upvotes: 4

Related Questions