

Discover more from Short Ruby Newsletter
A Monday summary of the articles, discussions, and news from the Ruby community
Over 4,000 subscribers
Continue reading
Rails 7.1 authenticate_by new method
#code #summary #rails71 #rails #ruby #authenticate_by
This is a summary for:
https://blog.kiprosh.com/rails-7-1-adds-authenticated_by/
The actual code:
# Code Summary for https://blog.kiprosh.com/rails-7-1-adds-authenticated_by/
# Part 1/2: Code sample
# User model
class User < ActiveRecord::Base
has_secure_password
end
# Before Rails 7.1
# To authenticate a user
User.find_by(username: "Alice")&.authenticate(password)
# In Rails 7.1
# do this to authenticate the user
User.authenticate_by(username: "Alice", password: password)
# Part 2/2: The why
# Why did this change from authenticating to authenticate_by?
# See: https://github.com/rails/rails/pull/43765
User.find_by(username: "Alice")&.authenticate(password)
# will return early if the username does not exist
# => vulnerable to timing-based enumeration attacks
User.authenticate_by(username: "Alice", password: password)
# From the PR:
# > Regardless of whether a record is found, +authenticate_by+ will
# > cryptographically digest the given password attributes. This behavior
# > helps mitigate timing-based enumeration attacks, wherein an attacker can
# > determine if a passworded record exists even without knowing the
# > password.