Bird
Raised Fist0
Ruby on Railsframework~15 mins

Remember me functionality in Ruby on Rails - Deep Dive

Choose your learning style10 modes available
Overview - Remember me functionality
What is it?
Remember me functionality lets a website keep you logged in even after you close your browser. It usually works by saving a special token in your browser's cookies. When you come back, the site reads this token to recognize you without asking for your password again. This makes using the site easier and faster.
Why it matters
Without remember me, users must log in every time they visit, which can be annoying and slow. Remember me improves user experience by saving time and effort. It also helps websites keep users engaged longer. Without it, many users might leave or avoid logging in repeatedly.
Where it fits
Before learning remember me, you should understand how user authentication and sessions work in Rails. After this, you can learn about security best practices for cookies and tokens, and advanced authentication gems like Devise.
Mental Model
Core Idea
Remember me works by storing a secure token in the browser that the server uses to identify a returning user without asking for credentials again.
Think of it like...
It's like leaving a special key under your doormat so the house knows it's you when you come back, without needing to knock or ring the bell.
┌───────────────┐       ┌───────────────┐
│ User logs in  │──────▶│ Server creates│
│ with checkbox │       │ token & saves │
│ 'Remember me' │       │ it in database│
└───────────────┘       └───────────────┘
         │                       │
         │                       ▼
         │               ┌───────────────┐
         │               │ Server sends  │
         │               │ token in cookie│
         │               └───────────────┘
         ▼                       │
┌───────────────┐               │
│ Browser saves │◀──────────────┘
│ cookie token  │
└───────────────┘
         │
         ▼
┌───────────────┐
│ User returns  │
│ Browser sends │
│ cookie token  │
└───────────────┘
         │
         ▼
┌───────────────┐
│ Server checks │
│ token matches │
│ user in DB   │
└───────────────┘
         │
         ▼
┌───────────────┐
│ User is logged│
│ in automatically│
└───────────────┘
Build-Up - 7 Steps
1
FoundationBasics of User Sessions in Rails
🤔
Concept: Learn how Rails manages user login sessions using cookies and session storage.
Rails uses a session hash to keep track of logged-in users. When a user logs in, Rails stores their user ID in the session. This session data is saved in a cookie on the browser. When the user makes requests, Rails reads the session cookie to know who they are.
Result
Users stay logged in during their browser session but lose login when the browser closes.
Understanding sessions is key because remember me extends this concept to persist login beyond browser sessions.
2
FoundationHow Cookies Store Data in Browsers
🤔
Concept: Cookies are small pieces of data saved by the browser and sent with every request to the server.
Cookies can store information like session IDs or tokens. They have properties like expiration time and security flags. By default, session cookies disappear when the browser closes, but cookies with expiration dates stay longer.
Result
You can control how long a cookie stays by setting its expiration.
Knowing cookie behavior helps you understand how remember me keeps users logged in across browser restarts.
3
IntermediateImplementing Remember Me Token Storage
🤔Before reading on: Do you think storing the user's password in a cookie is safe for remember me? Commit to your answer.
Concept: Instead of storing passwords, remember me uses a secure random token saved in both the database and a persistent cookie.
When a user logs in with remember me checked, the server generates a unique token and saves it in the database linked to the user. It also sends this token in a cookie with a long expiration date. On later visits, the server compares the cookie token with the database to authenticate the user.
Result
Users stay logged in even after closing and reopening the browser, without exposing sensitive data.
Understanding token storage prevents security risks like exposing passwords and enables safe persistent login.
4
IntermediateSecuring Remember Me Tokens
🤔Before reading on: Should remember me tokens be stored as plain text in the database? Commit to your answer.
Concept: Tokens should be securely hashed in the database to prevent misuse if the database leaks.
Instead of saving the raw token, Rails apps hash the token before saving it. When a cookie token arrives, the server hashes it and compares with the stored hash. This way, even if someone steals the database, they can't use the token directly.
Result
Remember me tokens are protected against theft and replay attacks.
Knowing token hashing is crucial for building secure authentication systems that protect user data.
5
IntermediateHandling Token Expiration and Revocation
🤔
Concept: Remember me tokens should expire and be revocable to maintain security over time.
Tokens have expiration dates set in cookies and server-side records. When expired, users must log in again. Also, tokens can be revoked on logout or suspicious activity by deleting or invalidating them in the database.
Result
Users stay logged in only as long as intended, reducing risk from stolen tokens.
Understanding expiration and revocation balances convenience with security in persistent login.
6
AdvancedIntegrating Remember Me in Rails with Secure Cookies
🤔Before reading on: Do you think setting cookies without the 'HttpOnly' and 'Secure' flags is safe? Commit to your answer.
Concept: Rails allows setting secure, HttpOnly cookies to protect remember me tokens from theft via JavaScript or insecure connections.
When setting the remember me cookie, use options like 'secure: true' to send cookies only over HTTPS and 'httponly: true' to prevent JavaScript access. This reduces risks like cross-site scripting stealing tokens.
Result
Remember me cookies are safer against common web attacks.
Knowing how to configure cookie flags is essential for protecting persistent login tokens in production.
7
ExpertAdvanced Token Rotation and Multi-Device Support
🤔Before reading on: Should the same remember me token be reused indefinitely across devices? Commit to your answer.
Concept: Advanced systems rotate tokens on each use and support multiple tokens per user for different devices.
Each time a user returns with a remember me token, the server verifies it, logs the user in, then generates a new token and updates the cookie and database. This prevents stolen tokens from being reused. Also, storing multiple tokens per user allows remembering multiple devices separately and revoking tokens individually.
Result
Improved security and flexibility for users with multiple devices.
Understanding token rotation and multi-device management prevents token replay attacks and improves user control.
Under the Hood
When a user logs in with remember me, Rails generates a secure random token and stores a hashed version in the database. It sends the raw token in a cookie with a long expiration. On subsequent requests, Rails reads the cookie token, hashes it, and compares it to the stored hash. If they match and the token is valid (not expired or revoked), Rails logs the user in automatically. Secure cookie flags prevent client-side scripts from accessing the token, and HTTPS ensures the token isn't sent over insecure connections.
Why designed this way?
This design balances user convenience with security. Storing hashed tokens prevents attackers from using stolen database data. Using cookies with expiration and secure flags protects tokens from theft and misuse. Alternatives like storing passwords or session IDs in cookies were rejected due to high security risks. Token rotation and multi-device support evolved to handle real-world threats and user needs.
┌───────────────┐
│ User logs in  │
│ with remember │
│ me checked    │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Server creates│
│ random token  │
│ and hashes it │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Save hashed   │
│ token in DB   │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Send raw token│
│ in cookie with│
│ secure flags  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Browser stores│
│ cookie        │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ User returns  │
│ Browser sends │
│ cookie token  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Server hashes │
│ token and     │
│ compares with │
│ DB hash       │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ If match and  │
│ valid, logs in│
│ user          │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Is it safe to store the user's password in a cookie for remember me? Commit to yes or no.
Common Belief:Some think storing the password in a cookie is fine for remember me because it's convenient.
Tap to reveal reality
Reality:Storing passwords in cookies is very unsafe because cookies can be stolen or read by attackers.
Why it matters:If passwords are stored in cookies, attackers can easily hijack accounts, causing serious security breaches.
Quick: Do you think remember me tokens can be stored as plain text in the database safely? Commit to yes or no.
Common Belief:Many believe storing tokens as plain text in the database is acceptable since tokens are random.
Tap to reveal reality
Reality:Tokens should be hashed in the database to prevent misuse if the database is compromised.
Why it matters:Plain text tokens can be stolen and used by attackers to impersonate users without needing passwords.
Quick: Do you think setting cookies without 'HttpOnly' and 'Secure' flags is safe? Commit to yes or no.
Common Belief:Some think cookie flags are optional and don't affect security much.
Tap to reveal reality
Reality:Without these flags, cookies can be stolen by JavaScript attacks or sent over insecure connections.
Why it matters:Missing flags expose tokens to theft, leading to account hijacking and data breaches.
Quick: Should the same remember me token be reused forever across devices? Commit to yes or no.
Common Belief:People often reuse the same token indefinitely for simplicity.
Tap to reveal reality
Reality:Tokens should be rotated on each use to prevent replay attacks and support multiple devices securely.
Why it matters:Reusing tokens allows attackers who steal tokens to log in repeatedly, compromising accounts.
Expert Zone
1
Remember me tokens should be unique per device to allow selective revocation without logging out all devices.
2
Token rotation on each use prevents replay attacks by invalidating old tokens immediately after use.
3
Secure cookie flags and SameSite attributes together reduce risks from cross-site scripting and cross-site request forgery.
When NOT to use
Remember me should not be used for highly sensitive applications like banking without additional verification. Alternatives include short session lifetimes with multi-factor authentication or hardware tokens.
Production Patterns
In production, remember me is often implemented with encrypted, signed cookies and integrated with authentication gems like Devise. Token rotation and device tracking are common to enhance security and user control.
Connections
Session Management
Remember me builds on session management by extending login persistence beyond browser sessions.
Understanding sessions helps grasp how remember me tokens maintain user identity over time.
Web Security (Cookies and XSS)
Remember me tokens rely on secure cookie practices to prevent theft via cross-site scripting attacks.
Knowing web security principles clarifies why cookie flags and token hashing are critical.
Physical Access Control Systems
Like remember me tokens, physical access cards store unique keys to grant entry without repeated identity checks.
Recognizing this similarity helps understand token-based authentication as a form of digital key management.
Common Pitfalls
#1Storing user passwords in cookies for remember me.
Wrong approach:cookies[:remember_token] = user.password
Correct approach:cookies.permanent.signed[:remember_token] = user.remember_token
Root cause:Misunderstanding that cookies should never hold sensitive data like passwords.
#2Saving raw remember me tokens in the database.
Wrong approach:user.update_attribute(:remember_token, raw_token)
Correct approach:user.update_attribute(:remember_digest, BCrypt::Password.create(raw_token))
Root cause:Not realizing tokens must be hashed to protect against database leaks.
#3Setting remember me cookies without secure flags.
Wrong approach:cookies.permanent[:remember_token] = raw_token
Correct approach:cookies.permanent.signed[:remember_token] = raw_token, secure: true, httponly: true
Root cause:Ignoring cookie security settings that prevent token theft.
Key Takeaways
Remember me functionality uses secure tokens stored in cookies to keep users logged in across browser sessions.
Tokens must be hashed in the database and protected with secure cookie flags to prevent theft and misuse.
Token expiration, revocation, and rotation are essential to balance convenience with security.
Implementing remember me correctly requires understanding sessions, cookies, and web security best practices.
Advanced implementations support multiple devices and prevent replay attacks by rotating tokens on each use.

Practice

(1/5)
1. What is the main purpose of the remember me functionality in a Rails application?
easy
A. To reset the user's password automatically
B. To keep users logged in by saving a cookie on their browser
C. To log out users after a short time
D. To encrypt all user data in the database

Solution

  1. Step 1: Understand the purpose of remember me

    The remember me feature is designed to keep users logged in even after they close their browser by saving a cookie.
  2. Step 2: Identify the correct description

    Options B, C, and D describe unrelated features like password reset, forced logout, or data encryption, which are not the purpose of remember me.
  3. Final Answer:

    To keep users logged in by saving a cookie on their browser -> Option B
  4. Quick Check:

    Remember me = save cookie to stay logged in [OK]
Hint: Remember me means saving login info in a cookie [OK]
Common Mistakes:
  • Confusing remember me with password reset
  • Thinking it logs out users quickly
  • Assuming it encrypts database data
2. Which of the following is the correct way to set a permanent signed cookie for remember me in Rails?
easy
A. cookies.signed[:user_id] = { value: user.id, expires: 20.years.from_now }
B. cookies[:user_id] = { value: user.id, expires: 1.hour.from_now }
C. session[:user_id] = user.id
D. cookies.permanent[:user_id] = user.id

Solution

  1. Step 1: Understand permanent signed cookies

    Permanent signed cookies in Rails are set with cookies.signed and an expiration far in the future, like 20 years.
  2. Step 2: Analyze options

    cookies[:user_id] = { value: user.id, expires: 1.hour.from_now } sets a cookie but expires in 1 hour, not permanent. session[:user_id] = user.id uses session, not cookie. cookies.permanent[:user_id] = user.id sets a permanent cookie but not signed, which is less secure.
  3. Final Answer:

    cookies.signed[:user_id] = { value: user.id, expires: 20.years.from_now } -> Option A
  4. Quick Check:

    Permanent signed cookie = cookies.signed with long expiry [OK]
Hint: Use cookies.signed with long expiry for remember me [OK]
Common Mistakes:
  • Using session instead of cookies
  • Setting short expiry for permanent cookie
  • Not signing the cookie for security
3. Given this Rails controller code snippet for login:
def create
  user = User.find_by(email: params[:email])
  if user&.authenticate(params[:password])
    if params[:remember_me] == '1'
      cookies.permanent.signed[:user_id] = user.id
    else
      session[:user_id] = user.id
    end
    redirect_to root_path
  else
    render :new
  end
end

What happens if the user checks the 'remember me' box?
medium
A. User ID is saved only in the session and lost on browser close
B. User password is saved in a cookie
C. User is logged out immediately
D. User ID is saved in a permanent signed cookie to keep logged in

Solution

  1. Step 1: Check the remember_me condition

    If params[:remember_me] == '1', the code sets cookies.permanent.signed[:user_id] = user.id, which saves a permanent signed cookie.
  2. Step 2: Understand cookie effect

    This cookie keeps the user logged in even after closing the browser, unlike session which clears on close.
  3. Final Answer:

    User ID is saved in a permanent signed cookie to keep logged in -> Option D
  4. Quick Check:

    Remember me checked = permanent signed cookie set [OK]
Hint: Remember me checked sets permanent signed cookie [OK]
Common Mistakes:
  • Thinking session is used when remember me is checked
  • Assuming password is saved in cookie
  • Believing user logs out immediately
4. Identify the bug in this logout method related to remember me functionality:
def destroy
  session.delete(:user_id)
  cookies.delete(:user_id)
  redirect_to login_path
end
medium
A. It does not clear the user's password
B. It deletes the cookie but not the session
C. It deletes the session but forgets to delete the signed cookie
D. It redirects to the wrong path

Solution

  1. Step 1: Check what is deleted

    The method deletes session[:user_id] and cookies[:user_id], but the remember me cookie is usually a signed cookie.
  2. Step 2: Understand cookie deletion

    Deleting cookies[:user_id] does not remove cookies.signed[:user_id]. The signed cookie remains, so user stays logged in.
  3. Final Answer:

    It deletes the session but forgets to delete the signed cookie -> Option C
  4. Quick Check:

    Logout must delete signed cookie too [OK]
Hint: Delete signed cookie on logout, not just plain cookie [OK]
Common Mistakes:
  • Deleting only session but not signed cookie
  • Deleting wrong cookie key
  • Not redirecting after logout
5. You want to implement a secure remember me feature that expires after 2 weeks and invalidates on logout. Which approach is best?
hard
A. Set cookies.signed[:user_id] with 2 weeks expiry and delete it on logout
B. Store user ID in session only and never use cookies
C. Save user password in a permanent cookie for quick login
D. Use a plain cookie without signing or expiry

Solution

  1. Step 1: Choose secure cookie with expiry

    Using cookies.signed[:user_id] with a 2 weeks expiry ensures the cookie is secure and expires reasonably.
  2. Step 2: Invalidate cookie on logout

    Deleting this cookie on logout prevents unauthorized access after user logs out.
  3. Final Answer:

    Set cookies.signed[:user_id] with 2 weeks expiry and delete it on logout -> Option A
  4. Quick Check:

    Secure signed cookie + expiry + delete on logout = best practice [OK]
Hint: Use signed cookie with expiry and delete on logout [OK]
Common Mistakes:
  • Storing password in cookie (insecure)
  • Using session only (no persistence after close)
  • Using unsigned or permanent cookies without expiry
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard