‘Has Secure Token’ in Rails
Rails is a framework written in Ruby used mainly for web development. I am trying here to give an insight about the “has secure token” which was introduced in Rails 5. In previous versions, secure token was not available, instead we 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.
How to add token into existing model ?
To add a secure token column to an existing model, use 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 which in turn 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
How to 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
Comment below for any further queries.
Have a Good Day !!