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
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?
EDIT: I've also tried the above with a fresh rails app generated by rails new --api
and I got the same behaviour.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…