Bird
Raised Fist0
Ruby on Railsframework~10 mins

Token-based authentication in Ruby on Rails - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Token-based authentication
User sends login request
↓
Server verifies credentials
↓
Generate token
↓
Send token to user
↓
User sends requests with token
↓
Server verifies token
Yes No↓
Allow access
This flow shows how a user logs in, receives a token, and uses it for future requests which the server verifies.
Execution Sample
Ruby on Rails
class ApplicationController < ActionController::API
  before_action :authenticate_user!

  def authenticate_user!
    token = request.headers['Authorization']&.split(' ')&.last
    user = User.find_by(authentication_token: token)
    render json: { error: 'Unauthorized' }, status: :unauthorized unless user
  end
end
This code checks the Authorization header for a token, finds the user, and rejects unauthorized requests.
Execution Table
StepActionInputToken ExtractedUser FoundResult
1Receive requestAuthorization: Bearer abc123abc123User with token abc123Proceed
2Verify tokenabc123abc123User foundAuthorized
3Receive requestAuthorization: Bearer invalidinvalidNo user foundReject with 401
4Verify tokeninvalidinvalidNo userUnauthorized response sent
💡 Execution stops when token is invalid or user not found, returning unauthorized response.
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
tokennilabc123abc123invalidinvalid
usernilUser objectUser objectnilnil
resultnilProceedAuthorizedRejectUnauthorized
Key Moments - 2 Insights
Why does the server reject the request when the token is missing or invalid?
Because in the execution_table rows 3 and 4, no user is found for the token, so the server returns an unauthorized response to protect resources.
How does the server extract the token from the Authorization header?
The server splits the header string by space and takes the last part as the token, as shown in the 'Token Extracted' column in the execution_table.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the token extracted at Step 1?
Ainvalid
Babc123
CBearer
Dnil
💡 Hint
Check the 'Token Extracted' column for Step 1 in the execution_table.
At which step does the server reject the request due to invalid token?
AStep 4
BStep 2
CStep 3
DStep 1
💡 Hint
Look at the 'Result' column where the response is 'Unauthorized response sent'.
If the token was missing from the header, how would the 'token' variable change in variable_tracker?
AIt would be 'Bearer'
BIt would be an empty string
CIt would be nil at all steps
DIt would be 'invalid'
💡 Hint
Refer to how 'token' is extracted from the header in the code and variable_tracker start value.
Concept Snapshot
Token-based authentication in Rails:
- User logs in and receives a token.
- Token sent in Authorization header as 'Bearer <token>'.
- Server extracts token, finds user by token.
- If user found, request allowed; else rejected with 401.
- Protects API endpoints without sessions or cookies.
Full Transcript
Token-based authentication in Rails works by the user sending a login request. The server checks the credentials and if valid, generates a token and sends it back. The user includes this token in the Authorization header for future requests. The server extracts the token from the header, looks up the user by this token, and if found, allows access. If the token is missing or invalid, the server rejects the request with an unauthorized error. This method avoids using sessions and cookies, making it suitable for APIs.

Practice

(1/5)
1. What is the main purpose of token-based authentication in Rails?
easy
A. To identify users securely without requiring passwords every time
B. To store user passwords in plain text
C. To create server sessions for each user
D. To encrypt database records automatically

Solution

  1. Step 1: Understand token-based authentication

    Token-based authentication uses a secret token to identify users securely without needing passwords repeatedly.
  2. Step 2: Compare options

    Only To identify users securely without requiring passwords every time correctly describes this purpose; others describe unrelated or incorrect behaviors.
  3. Final Answer:

    To identify users securely without requiring passwords every time -> Option A
  4. Quick Check:

    Token-based authentication = Identify users securely without passwords [OK]
Hint: Tokens replace passwords for repeated user identification [OK]
Common Mistakes:
  • Confusing tokens with password storage
  • Thinking tokens create server sessions
  • Assuming tokens encrypt data automatically
2. Which Rails method adds a secure token to a model for token-based authentication?
easy
A. has_secure_password
B. validates_token
C. has_secure_token
D. generate_token

Solution

  1. Step 1: Recall Rails token helper methods

    Rails provides has_secure_token to add a secure token to models easily.
  2. Step 2: Eliminate incorrect options

    has_secure_password is for passwords, not tokens; others are not valid Rails methods.
  3. Final Answer:

    has_secure_token -> Option C
  4. Quick Check:

    Token method in Rails = has_secure_token [OK]
Hint: Remember: token method is 'has_secure_token' not 'password' [OK]
Common Mistakes:
  • Confusing has_secure_token with has_secure_password
  • Using non-existent methods like generate_token
  • Assuming validates_token is built-in
3. Given the model code:
class User < ApplicationRecord
  has_secure_token :auth_token
end

user = User.new
user.save
puts user.auth_token.nil?

What will be the output?
medium
A. false
B. Error: undefined method
C. nil
D. true

Solution

  1. Step 1: Understand has_secure_token behavior

    When a new User is saved, Rails automatically generates a unique token for auth_token, so it won't be nil.
  2. Step 2: Evaluate the output of puts user.auth_token.nil?

    Since auth_token is set, nil? returns false, so output is false.
  3. Final Answer:

    false -> Option A
  4. Quick Check:

    Token generated on save = false for nil? [OK]
Hint: Tokens auto-generate on save, so nil? returns false [OK]
Common Mistakes:
  • Assuming token is nil before save
  • Expecting nil output instead of false
  • Confusing method names causing errors
4. Identify the error in this token authentication setup:
class ApiUser < ApplicationRecord
  has_secure_token :auth_token
end

user = ApiUser.new
user.auth_token = nil
user.save
puts user.auth_token.nil?
medium
A. user.save will raise an exception due to nil token
B. has_secure_token requires a token column named 'token', not 'auth_token'
C. Token is not generated because auth_token was manually set to nil before save
D. No error; output will be false

Solution

  1. Step 1: Recall has_secure_token generation condition

    has_secure_token :auth_token generates a token if auth_token.blank? before save (nil.blank? returns true).
  2. Step 2: Trace code execution

    Setting user.auth_token = nil keeps it blank, so save generates the token. user.auth_token.nil? returns false. No error.
  3. Final Answer:

    No error; output will be false -> Option D
  4. Quick Check:

    nil.blank? = true -> generates token [OK]
Hint: Setting to nil does NOT prevent generation; nil.blank? = true [OK]
Common Mistakes:
  • Thinking setting to nil prevents token generation
  • Expecting save to raise error on nil token
  • Thinking output is true because manually set to nil
5. You want to secure an API in Rails using token-based authentication. Which approach correctly checks the token sent in request headers against the stored user token?
hard
A. Store tokens in cookies and check them with session[:token]
B. Use before_action to find user by auth_token from request.headers['Authorization'] and reject if not found
C. Use has_secure_password to verify token in params
D. Generate a new token on every request and compare with stored token

Solution

  1. Step 1: Understand token authentication in APIs

    APIs commonly send tokens in headers; Rails can check request.headers['Authorization'] to find the user.
  2. Step 2: Evaluate options for correctness

    Use before_action to find user by auth_token from request.headers['Authorization'] and reject if not found correctly uses before_action to authenticate by token. Options B and C misuse cookies and password helpers. Generate a new token on every request and compare with stored token is insecure and impractical.
  3. Final Answer:

    Use before_action to find user by auth_token from request.headers['Authorization'] and reject if not found -> Option B
  4. Quick Check:

    API token check = before_action with header token [OK]
Hint: Check token in headers with before_action for API security [OK]
Common Mistakes:
  • Using cookies or sessions for API token storage
  • Confusing password helpers with token verification
  • Generating new token each request causing mismatch
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