Skip to content
RY

Has secure token in rails 5

Ram Laxman Yadav1 min read

Today I gona discuss about the ActiveRecord::Base#has_secure_password method, in rails 5 it became has_secure_token, it specifies that an attribute of your model should be used to store a unique 24-character alphanumeric token. Tokens such as this are often used in Rails applications for providing token-based API access or allowing one-time access for password reset actions. Since it is such a common use case, it’s very convenient to have it built into Rails.

Add token into existing model:

To add a secure token column to an existing model, you can use the migration generator:

  • rails g migration add_auth_token_to_users auth_token:token.

This creates a migration to add a string column called auth_token and adds a unique index on that column, as shown in the following code:

class AddAuthTokenToUsers < ActiveRecord::Migration
def change
add_column :users, :auth_token, :string
add_index :users, :auth_token, unique: true
end
end

Add Secure Token in model:

class User < ActiveRecord::Base
has_secure_token :auth_token
end

The name of the model attribute defaults to token if no name for the column is specified.The actual token value is generated in a before_create handler, so the value is only available after you have successfully created an item. After that, the value does not subsequently change, as shown here:

user = User.new
user.auth_token
# nil will be returned
user.save
user.auth_token
# it will return some token like cSlvzXl6kVvWUj4iNahElQ

Multiple Tokens:

You can specify multiple token attributes in a model, simply by adding additional has_secure_token statements.

class User < ActiveRecord::Base
has_secure_token :auth_token
has_secure_token :password_reset_token
end

Regenerating the Token:

If you want to generate token and save it to the database, you can now use regenerate_token method to generate new token:

user.auth_token
# cSlvzXl6kVvWUj4iNahElQ
user.regenerate_token
# xr4naoc77wYATGehnFb5Mg