How to use Rails’s has_secure_password feature
24 March 2022 (Updated 24 March 2022)
Install gem
Add to Gemfile:
gem 'bcrypt', '~> 3.1.7'
Run:
./bin/bundle install
Configure database table
Ensure your user table has a column named XXX_digest
where XXX
is the attribute name containing the user password. Typically, this will be password_digest
.
Configure user model
class User < ActiveRecord::Base
has_secure_password
end
Authenticate password
User.first.authenticate('some-password')
has_secure_password
will encrypt the given password and compare it against the encrypted password in the database. If they match, User
is returned. Otherwise, false
is returned.
Notes
Including has_secure_password
will add the following validations:
- Password must be present on creation
- Password length should be less than or equal to 72 bytes
- Confirmation of password (using a
XXX_confirmation
attribute)
Sources
Tagged:
Rails
Thanks for your comment 🙏. Once it's approved, it will appear here.
Leave a comment