invalid csrf token
-
Use-case
- User (browser) submit todo item to server, using route
POST '/todo'.
- Server will check if user is logon. If not logon, redirect to logon page -
middleware.ensureLoggedIn()
However, the server throws "invalid csrf token" message. I believe this is caused by redirecting using
POST '/login'
instead ofGET '/login'
, which is incorrect.Is there anyway to handle such a common usecase?
Please advise me. Thanks! - User (browser) submit todo item to server, using route
-
You can send the csrf token with your post request as "_csrf".
The token is stored at config.csrf_token
Something like this should work
<input id="csrf" type="hidden" name="_csrf"> // Inside your form. ... <script>$('#csrf').val(config.csrf_token);</script>
You can also get the token from
/api/config
if you're using this for an app or cURLing. -
Thanks @yariplus for your reply.
Let me elaborate my usecase with more details:
- New user (not logon) come to xyz.com's TODO page.
- New user trying out feature (eg. adding a TODO item) by clicking "Add" button.
- "Add" button will send a post to server.
- Server check user is not logon, and so will redirect new user to login page.
As you know, the exception is thrown on step 4, due to "invalid csrf token". So if I understand you correctly, I will need to embed a csrf token on TODO page?
-
Actually, I'm not quite sure what is happening. You should always include a csrf token in a form, but that doesn't seem related to your problem.
It appears to be like you said and the redirect is POSTing to
/login
.