0
0
Ruby on Railsframework~20 mins

Token-based authentication in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Token Auth Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
component_behavior
intermediate
2:00remaining
What does this Rails controller action return when a valid token is provided?

Consider this Rails API controller action that uses token-based authentication. What will be the JSON response if the token is valid?

Ruby on Rails
class Api::V1::ProfilesController < ApplicationController
  before_action :authenticate_user!

  def show
    render json: { email: current_user.email, name: current_user.name }
  end

  private

  def authenticate_user!
    token = request.headers['Authorization']&.split(' ')&.last
    user = User.find_by(authentication_token: token)
    if user
      @current_user = user
    else
      render json: { error: 'Unauthorized' }, status: :unauthorized
    end
  end

  def current_user
    @current_user
  end
end
A500 Internal Server Error
B{"email": null, "name": null}
C{"email": "user@example.com", "name": "Alice"}
D{"error": "Unauthorized"}
Attempts:
2 left
💡 Hint

Think about what happens when the token matches a user in the database.

📝 Syntax
intermediate
2:00remaining
Which option correctly defines a method to generate a secure token in a Rails model?

You want to add a method in your Rails User model that generates a unique authentication token. Which code snippet is syntactically correct and secure?

Ruby on Rails
class User < ApplicationRecord
  before_create :generate_authentication_token

  private

  def generate_authentication_token
    # Which option is correct here?
  end
end
Aself.authentication_token = SecureRandom.hex(20)
Bauthentication_token = SecureRandom.hex(20)
Cself.authentication_token = SecureRandom.random_number(20)
Dauthentication_token = SecureRandom.base64(20)
Attempts:
2 left
💡 Hint

Remember to assign to the attribute with self. inside instance methods.

state_output
advanced
2:00remaining
What is the value of current_user after this request with an invalid token?

Given this controller snippet, what will current_user be if the token is invalid?

Ruby on Rails
class Api::V1::SessionsController < ApplicationController
  before_action :authenticate_user!

  def index
    render json: { user: current_user&.email }
  end

  private

  def authenticate_user!
    token = request.headers['Authorization']&.split(' ')&.last
    user = User.find_by(authentication_token: token)
    if user
      @current_user = user
    else
      render json: { error: 'Unauthorized' }, status: :unauthorized
    end
  end

  def current_user
    @current_user
  end
end
AUser object with email "guest@example.com"
Bnil
CRaises NoMethodError
D"" (empty string)
Attempts:
2 left
💡 Hint

What happens if the token does not match any user?

🔧 Debug
advanced
2:00remaining
Why does this token authentication code always return 'Unauthorized' even with a valid token?

Examine this code snippet. It should authenticate users by token but always returns 'Unauthorized'. What is the bug?

Ruby on Rails
def authenticate_user!
  token = request.headers['Authorization']&.split(' ')&.last
  user = User.find_by(authentication_token: token)
  if user.nil?
    render json: { error: 'Unauthorized' }, status: :unauthorized
  else
    @current_user = user
  end
end
AThe token is not stripped of whitespace before lookup, causing find_by to fail
BThe method returns before setting @current_user because render does not halt execution
CThe condition should check if user is present, not nil
DThe token variable is nil because the header key is case-sensitive and should be 'authorization'
Attempts:
2 left
💡 Hint

Check how the token string is extracted and used.

🧠 Conceptual
expert
2:00remaining
Which statement best explains the security benefit of token-based authentication over session-based authentication in Rails APIs?

Choose the most accurate explanation of why token-based authentication is preferred for APIs compared to traditional session-based authentication.

ASessions require HTTPS, but tokens can be safely sent over HTTP without encryption.
BTokens automatically expire after 5 minutes, making them more secure than sessions which never expire.
CToken-based authentication requires cookies, which are more secure than headers used in session authentication.
DTokens are stored on the client and sent with each request, avoiding server-side session storage and enabling stateless APIs.
Attempts:
2 left
💡 Hint

Think about how APIs handle user state and scalability.