Bird
Raised Fist0
Ruby on Railsframework~20 mins

CSRF protection in Ruby on Rails - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
CSRF Protection Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ component_behavior
intermediate
2:00remaining
What happens when a Rails form is submitted without a CSRF token?

Consider a Rails application with default CSRF protection enabled. What will happen if a form is submitted without including the CSRF token?

AThe server will reject the request with an <strong>ActionController::InvalidAuthenticityToken</strong> error.
BThe server will accept the request and process it normally without any error.
CThe server will redirect the user to the login page automatically.
DThe server will log a warning but still process the request.
Attempts:
2 left
💡 Hint

Think about what Rails does to protect against forged requests.

📝 Syntax
intermediate
2:00remaining
Which code snippet correctly includes the CSRF token in a Rails form?

In Rails views, which code snippet correctly ensures the CSRF token is included in the form?

A<code>&lt;form&gt;&lt;input type='hidden' name='csrf_token' value='&lt;%= csrf_token %&gt;'&gt;&lt;/form&gt;</code>
B<code>&lt;form&gt;&lt;%= csrf_meta_tags %&gt;&lt;/form&gt;</code>
C<code>&lt;%= form_with model: @post do |form| %&gt;&lt;/form&gt;</code>
D<code>&lt;form&gt;&lt;input type='hidden' name='authenticity_token' value='&lt;%= form_authenticity_token %&gt;'&gt;&lt;/form&gt;</code>
Attempts:
2 left
💡 Hint

Look for the correct hidden input name and method to get the token.

🔧 Debug
advanced
2:00remaining
Why does disabling CSRF protection cause a security risk?

A developer disables CSRF protection in a Rails controller using skip_before_action :verify_authenticity_token. What is the main security risk introduced?

AThe application will crash when receiving POST requests.
BAttackers can trick users into submitting unwanted requests on their behalf, potentially changing data without consent.
CUsers will be logged out automatically after each request.
DThe server will reject all AJAX requests.
Attempts:
2 left
💡 Hint

Think about what CSRF protection prevents.

🧠 Conceptual
advanced
2:00remaining
How does Rails verify the CSRF token on incoming requests?

Which statement best describes how Rails verifies the CSRF token on POST, PATCH, PUT, or DELETE requests?

ARails verifies the token by decoding a JWT sent in the request headers.
BRails checks if the token matches a value stored in a cookie named <code>csrf_token</code>.
CRails compares the token submitted in the form data or headers with the token stored in the user session.
DRails does not verify tokens on non-GET requests by default.
Attempts:
2 left
💡 Hint

Consider where Rails stores the token and how it compares it.

❓ state_output
expert
2:00remaining
What is the value of session[:_csrf_token] after a valid form submission?

Given a Rails app with default CSRF protection, after a user submits a valid form with a correct CSRF token, what happens to session[:_csrf_token]?

AIt remains the same as before the request, preserving the token for future requests.
BIt is cleared and set to <code>nil</code> after each valid request.
CIt changes to a new random token after each valid form submission.
DIt stores the submitted token value from the form for the current request only.
Attempts:
2 left
💡 Hint

Think about token reuse and session persistence.

Practice

(1/5)
1. What is the main purpose of CSRF protection in a Rails application?
easy
A. To prevent unauthorized commands from being executed by malicious websites
B. To speed up database queries
C. To improve the user interface design
D. To encrypt user passwords

Solution

  1. Step 1: Understand CSRF meaning

    CSRF stands for Cross-Site Request Forgery, which is an attack where unauthorized commands are sent from a user that the web application trusts.
  2. Step 2: Identify CSRF protection goal

    The goal of CSRF protection is to stop these unauthorized commands from malicious websites.
  3. Final Answer:

    To prevent unauthorized commands from being executed by malicious websites -> Option A
  4. Quick Check:

    CSRF protection = prevent unauthorized commands [OK]
Hint: CSRF stops bad actions from other sites [OK]
Common Mistakes:
  • Confusing CSRF with password encryption
  • Thinking it speeds up queries
  • Assuming it improves UI design
2. Which line of code correctly enables CSRF protection in a Rails controller?
easy
A. use_csrf_token()
B. enable_csrf_protection true
C. csrf_protect = true
D. protect_from_forgery with: :exception

Solution

  1. Step 1: Recall Rails CSRF syntax

    Rails uses the method protect_from_forgery with options like :exception to enable CSRF protection.
  2. Step 2: Match correct syntax

    Only protect_from_forgery with: :exception is valid Rails syntax to enable CSRF protection.
  3. Final Answer:

    protect_from_forgery with: :exception -> Option D
  4. Quick Check:

    Enable CSRF = protect_from_forgery [OK]
Hint: Use protect_from_forgery with: :exception [OK]
Common Mistakes:
  • Using non-existent methods like enable_csrf_protection
  • Assigning variables instead of calling method
  • Calling undefined functions like use_csrf_token()
3. Given this Rails form code snippet, what happens if the CSRF token is missing or invalid?
<%= form_with url: '/posts' do |form| %>
  <%= form.text_field :title %>
  <%= form.submit 'Create' %>
<% end %>
medium
A. The form submits successfully without any error
B. Rails raises an ActionController::InvalidAuthenticityToken error
C. The form data is saved but with a warning in logs
D. The form redirects to the home page silently

Solution

  1. Step 1: Understand form_with and CSRF token

    Rails automatically includes a CSRF token in forms created with helpers like form_with.
  2. Step 2: Effect of missing or invalid token

    If the token is missing or invalid, Rails raises an ActionController::InvalidAuthenticityToken error to block the request.
  3. Final Answer:

    Rails raises an ActionController::InvalidAuthenticityToken error -> Option B
  4. Quick Check:

    Missing CSRF token = InvalidAuthenticityToken error [OK]
Hint: Missing token causes InvalidAuthenticityToken error [OK]
Common Mistakes:
  • Assuming form submits without error
  • Thinking data saves with warning
  • Believing it redirects silently
4. You see this error in your Rails app: ActionController::InvalidAuthenticityToken. Which fix will most likely solve the problem?
medium
A. Ensure your forms include the CSRF token by using Rails form helpers
B. Remove the CSRF token from your forms
C. Add protect_from_forgery with: :exception in ApplicationController
D. Disable CSRF protection in config

Solution

  1. Step 1: Identify cause of InvalidAuthenticityToken

    This error happens when the CSRF token is missing or invalid in the form submission.
  2. Step 2: Choose fix to include CSRF token

    Using Rails form helpers like form_with automatically includes the CSRF token, fixing the error.
  3. Final Answer:

    Ensure your forms include the CSRF token by using Rails form helpers -> Option A
  4. Quick Check:

    Fix InvalidAuthenticityToken = include CSRF token [OK]
Hint: Use Rails form helpers to add CSRF token automatically [OK]
Common Mistakes:
  • Adding protect_from_forgery again when already present
  • Removing CSRF token which causes error
  • Disabling protection instead of fixing token
5. You want to allow JSON API requests in your Rails app without CSRF errors but keep protection for HTML forms. Which is the best way to do this?
hard
A. Manually add CSRF tokens to JSON requests
B. Disable CSRF protection globally
C. Use protect_from_forgery with: :null_session and handle API authentication separately
D. Use protect_from_forgery with: :exception and skip CSRF check for JSON requests

Solution

  1. Step 1: Understand CSRF and API requests

    CSRF tokens are mainly for browser forms; API JSON requests often don't use them and need different handling.
  2. Step 2: Choose best Rails approach

    Using protect_from_forgery with: :null_session disables CSRF exceptions for APIs but keeps protection for forms, requiring separate API authentication.
  3. Final Answer:

    Use protect_from_forgery with: :null_session and handle API authentication separately -> Option C
  4. Quick Check:

    API JSON + CSRF = null_session + separate auth [OK]
Hint: Use null_session for APIs, keep exception for forms [OK]
Common Mistakes:
  • Disabling CSRF protection globally
  • Trying to add CSRF tokens manually to JSON
  • Skipping CSRF only without alternative auth
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