Complete the code to enable CSRF protection in a Rails controller.
class ApplicationController < ActionController::Base protect_from_forgery with: [1] end
The protect_from_forgery method with :exception option raises an exception on CSRF attacks, which is the default and recommended way in Rails.
Complete the code to include the CSRF token in a Rails form helper.
<%= form_with url: '/posts' do |form| %> [1] <%= form.submit 'Create' %> <% end %>
The CSRF token is included as a hidden field with the token value to protect the form submission.
Fix the error in the controller to skip CSRF protection for API requests.
class ApiController < ActionController::API [1] :verify_authenticity_token end
To disable CSRF protection for API controllers, use skip_before_action :verify_authenticity_token.
Complete the code to create a hash of form data including the CSRF token.
form_data = {
authenticity_token: [1],
post: { title: 'Hello', content: 'World' },
}The method form_authenticity_token() returns the CSRF token string. A comma is needed to separate hash entries.
Fill all three blanks to verify the CSRF token in a custom controller action.
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
The CSRF token parameter is :authenticity_token. The method valid_authenticity_token? returns true or false, so the if condition is correct. The HTTP status code for forbidden is 403.