‘Has’ Secure Token in Rails

Rails is an framework written in Ruby used mainly for web development. The writer is giving an insight about the “has secure token” which is introduced in Rails 5. In previous versions, secure token was not available, instead they had:

ActiveRecord::Base#has_secure_password method

“has_secure_token”, in Rails 5, specifies that an attribute of your model should be used to store a unique 24-character alphanumeric token. Tokens like this are often used in Rails applications for providing token-based API access or allowing one-time access for password reset actions.

Add token into existing model:

To add a secure token column to an existing model, migration generator:

*rails g migration add_auth_token_to_users auth_token:token

can be used.

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:

Multiple token attributes can be specified 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:

To generate token and save it to the database, one can now use “regenerate_token” method to generate new token:

user.auth_token 
# cSlvzXl6kVvWUj4iNahElQ
user.regenerate_token
# xr4naoc77wYATGehnFb5Mg
One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.