Getting a CSRF error (403 - Forbidden)
mesosteros opened this issue · 5 comments
Ok, I have the everything up and running until the forms (also following the example you provide). When I click the buttons to submit a request I get a CSRF error.
On the browser console it says:
POST http://localhost:4000/register 403 (Forbidden)
send @ jquery.js:8630
ajax @ jquery.js:8166
jQuery.each.jQuery.(anonymous function) @ jquery.js:8311
(anonymous function) @ (index):110
dispatch @ jquery.js:4435
jQuery.event.add.elemData.handle @ jquery.js:4121
And also:
XHR finished loading: POST "http://localhost:4000/register".
send @ jquery.js:8630
ajax @ jquery.js:8166
jQuery.each.jQuery.(anonymous function) @ jquery.js:8311
(anonymous function) @ (index):110
dispatch @ jquery.js:4435
jQuery.event.add.elemData.handle @ jquery.js:4121
On my console I have:
** (exit) an exception was raised:
** (Plug.CSRFProtection.InvalidCSRFTokenError) invalid CSRF (Cross Site Forgery Protection) token, make sure all requests include a '_csrf_token' param or an 'x-csrf-
token' header
(plug) lib/plug/csrf_protection.ex:132: Plug.CSRFProtection.call/2
(loginSystem) web/router.ex:5: LoginSystem.Router.browser/2
(loginSystem) web/router.ex:1: LoginSystem.Router.do_call/2
(loginSystem) lib/loginSystem/endpoint.ex:1: LoginSystem.Endpoint.phoenix_pipeline/1
(loginSystem) lib/plug/debugger.ex:90: LoginSystem.Endpoint."call (overridable 3)"/2
(loginSystem) lib/phoenix/endpoint/render_errors.ex:34: LoginSystem.Endpoint.call/2
(plug) lib/plug/adapters/cowboy/handler.ex:15: Plug.Adapters.Cowboy.Handler.upgrade/4
(cowboy) src/cowboy_protocol.erl:442: :cowboy_protocol.execute/4
@mesosteros that has to do with the builtin CSRF protection in Phoenix. You'll have to inject the CSRF header on the ajax request, check the accepted answer here, or... you could also skip it on your routes, but don't quote me on that 😛
I already tried that. And in the example you provide you don't use <form>
.
By the way, I'm not getting the error anymore but nothing happens now (I wasn't using the jquery-ujs because I was asked not to). The problem is that nothing is being saved on the database or sent to my email.
@mesosteros but does the request reach the server?
I don't know now. With the CSRF error it was because the message also displayed in the server. But now without the error no feedback is being given.
@mesosteros I've added a quick guide to have the layouts and controllers work out of the box here. In case you need to use CSRF Tokens for the templates you can also use this configuration.
Closing the issue for now, feel free to re-open in case the issue persists.