I have a Rails 5 API application ( ApplicationController < ActionController::API ). The need came to add a simple GUI form for one endpoint of this API.
I originally got ActionView::Template::Error undefined method protect_against_forgery? when trying to process the form. I added the include ActionController::RequestForgeryProtection and protect_from_forgery with:exception to this endpoint. What solved this problem was as expected.
However, when I try to submit this form, I get: 422 Unprocessable Entity ActionController::InvalidAuthenticityToken . I added <%= csrf_meta_tags %> and confirmed that meta: csrf-param and meta: csrf-token are present in my headers and that authenticity_token present in my form. (The tokens themselves are different from each other.)
I tried protect_from_forgery prepend: true, with:exception , no effect. I can "fix" this problem by commenting: protect_from_forgery with:exception . But I understand that this disables CSRF protection in my form. (I want CSRF protection.)
What am I missing?
UPDATE:
To make this clear, 99% of this application is a pure JSON RESTful API. The need came to add one HTML view and form to this application. Therefore, for one controller, I want to enable full CSRF protection. The rest of the application does not need CSRF and can remain unchanged.
UPDATE 2:
I simply compared the page source of this form of the HTML application and the title with another regular Rails 5 application that I wrote. authenticity_token in the header and authenticity_token in the form are the same. I have a problem in the API application, they are different. Maybe something?
UPDATE 3:
Well, that is not a problem. However, in a further comparison between running and non-working applications, I noticed that there is nothing in Network> Cookies. I see a bunch of things like _my_app-session in the cookies of the working application.
security ruby-on-rails ruby-on-rails-5 csrf
lostphilosopher
source share