I recently converted an existing Rails 6 application to an API-only application following this guide as well as some helpful information from here.
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
protect_from_forgery with: :exception
cookies['X-CSRF-Token'] = form_authenticity_token
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:
API mode app:
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?
EDIT: I've also tried the above with a fresh rails app generated by
rails new --api and I got the same behaviour.