My frontend application uses session cookies to maintain authentication with the server (with a rack-cors setup) and all that works when I manually test it. Since I’m using a session cookie, I added CSRF protection with a cookie in my application controller like this:
class ApplicationController < ActionController::API include ActionController::Cookies include ActionController::RequestForgeryProtection protect_from_forgery with: :exception after_action :set_csrf_cookie def set_csrf_cookie cookies['X-CSRF-Token'] = form_authenticity_token end
The problem I’m having is that my rspec tests are all failing with CSRF-related issues. Usually CSRF is disabled in the test environment in rails (as documented here), however I ran
rails console -e test the following on both the API app and the old app and got a discrepancy:
Regular rails app:
Rails.application.config.action_controller.allow_forgery_protection >> false ApplicationController.allow_forgery_protection >> false
API mode app:
Rails.application.config.action_controller.allow_forgery_protection >> false ApplicationController.allow_forgery_protection >> true
Sure enough, when I disable CSRF protection completely, the tests start looking better.
Is there anyway to restore this behaviour in a Rails API app?
I’ve also tried the above with a fresh rails app generated by
rails new --api and I got the same behaviour.