0
0
Ruby on Railsframework~10 mins

CSRF protection in Ruby on Rails - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to enable CSRF protection in a Rails controller.

Ruby on Rails
class ApplicationController < ActionController::Base
  protect_from_forgery with: [1]
end
Drag options to blanks, or click blank then click option'
A:exception
B:null_session
C:reset_session
D:allow
Attempts:
3 left
💡 Hint
Common Mistakes
Using :null_session disables raising errors and may allow unsafe requests.
Using :allow does not protect against CSRF attacks.
2fill in blank
medium

Complete the code to include the CSRF token in a Rails form helper.

Ruby on Rails
<%= form_with url: '/posts' do |form| %>
  [1]
  <%= form.submit 'Create' %>
<% end %>
Drag options to blanks, or click blank then click option'
Aform.hidden_field :authenticity_token, value: form.authenticity_token
Bform.authenticity_token
Ccsrf_meta_tags
Dform.hidden_field :authenticity_token
Attempts:
3 left
💡 Hint
Common Mistakes
Using csrf_meta_tags inside the form does not add the token field.
Using form.authenticity_token alone does not create a form input.
3fill in blank
hard

Fix the error in the controller to skip CSRF protection for API requests.

Ruby on Rails
class ApiController < ActionController::API
  [1] :verify_authenticity_token
end
Drag options to blanks, or click blank then click option'
Aaround_action
Bbefore_action
Cafter_action
Dskip_before_action
Attempts:
3 left
💡 Hint
Common Mistakes
Using before_action adds the check instead of skipping it.
Using after_action or around_action is not correct for skipping CSRF.
4fill in blank
hard

Complete the code to create a hash of form data including the CSRF token.

Ruby on Rails
form_data = {
  authenticity_token: [1],
  post: { title: 'Hello', content: 'World' },
}
Drag options to blanks, or click blank then click option'
Aform_authenticity_token
Bform_authenticity_token()
C,
D;
Attempts:
3 left
💡 Hint
Common Mistakes
Omitting parentheses on the method call.
Using a semicolon instead of a comma in the hash.
5fill in blank
hard

Fill all three blanks to verify the CSRF token in a custom controller action.

Ruby on Rails
def verify_token
  token = params[[1]]
  if valid_authenticity_token?(session, token) [2]
    render plain: 'Valid token'
  else
    render plain: 'Invalid token', status: [3]
  end
end
Drag options to blanks, or click blank then click option'
A:authenticity_token
B:csrf_token
C403
D422
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong param key like :csrf_token.
Using 422 status code which means unprocessable entity.