Ad

Laravel API Requests With CSRF Token

- 1 answer

I am creating a website using the Laravel framework where I am using jQuery instead of Vue. And I am wondering which approach is best to use when executing post requests securely when already logged in.

I am currently using Laravel's default authentication and web/routes to display correct views when logged in.

And now for a smoother user experience I want to use jQuery POST requests instead of submitting a form so I can retrieve JSON and do the necessary changes without a website reload.

Have some experience with JWT and OAuth2, but is this really necessary in this case?

Found this thread: https://stackoverflow.com/a/44106621/2906013 which explains that it's bad practice sending the CSRF-token in the POST-request header since REST API's are stateless. But this state is already set when the user is logged in, so I don't understand the harm this can cause in my case?

What makes this so different from a JWT token? Both of them is a token representing a logged in user or am I wrong (CSRF token is session token in Laravel if I am not wrong) ?

Want to make sure the website is secured properly, so all feedback is highly appreciated.

Ad

Answer

In my personal openion it depends on how do you categorise your ajax request and project structure in general. Is your project entirely restful? Like all requests need to be RESTful and there is no login directly? In that case your application is stateless and each request will need some sort of authentication which will not be ideal way doing through csrf_token.

For example, if you use a 3rd party API, you never login actually but you use JWT or OAUTH tokens to make sure your request is authenticated.

Now in your case, if you have entire website basically following the non-restful redirect strategy, and maintaining session then it is stateful. The session is what maintaining its state. So for simple form saving if you want to use ajax instead of refreshing the page, sending csrf_token would be totally alright.

Internally laravel is not much concerned about how you are sending the POST request in this case, if it is via refresh-submit or an ajax. So ideally nothing is changing just you will return json instead of a redirect and handle it in javascript.

The security of this will depend upon how properly you validate your post request in controller, how do you make sure invalid data is not sent to server etc.

Ad
source: stackoverflow.com
Ad