janko / rodauth-rails

Rails integration for Rodauth authentication framework
https://github.com/jeremyevans/rodauth
MIT License
571 stars 40 forks source link

Can't verify CSRF token authenticity when make a post request with body using request.js #98

Closed brunoprietog closed 2 years ago

brunoprietog commented 2 years ago

Hi,

I am trying to make a post request using request.js, the rails library for making requests through javascript injecting headers automatically to make checks like CSRF. When including parameters in the body of the post request, Rails shows a big error saying Can't verify CSRF token authenticity. I reported this error in request.js and then was asked for an example repository. Building it from 0, I noticed that the error does not occur, so I copied my rodauth configuration and was able to reproduce the error again, so I suspect this is where the problem lies.

This is the example repository and this is the originally reported issue, in case it is a request.js problem.

I would appreciate any help.

Thanks!

janko commented 2 years ago

Thanks for the report, I will take a look. Interesting that it happens on application endpoints, I was expecting it would only happen on Rodauth endpoints.

janko commented 2 years ago

I wasn't able to reproduce the CSRF error in your example app. After correcting it to add :en to available locales, and set config.action_mailer.default_url_options, I was getting 401 Unauthorized responses from POST /my_endpoint. This is because the JWT feature is enabled, which requires the JWT token to be passed in the Authorization request header on JSON requests, and none was provided in the AJAX request. Once I disabled the JWT feature (leaving on the JSON feature), the AJAX request was successful.

One confusing thing was that rodauth-rails wasn't displaying the response status in rails logs when rodauth.require_authentication in the controller returned the 401 Unauthorized response. I will need to fix that.

janko commented 2 years ago

Since I wasn't able to reproduce the CSRF error, I will close this issue for now. I can reopen once I receive more information.

I will definitely follow up with the fix for logging the response statuses, I just haven't quite worked out how to solve it.