Yes you can. I recommend using Sanctum for that. They are not really csrf tokens but they are similar.
CSRF Protection with API methods
Hello,
Is it possible to have csrf protection with api methods ? I think it's a little different, because now I'm working with two differents applications so I don't know how can I put CSRF protection on a POST API method.
I don't know if i've explain myself correctly (sorry for my english).
Thanks for your help.
Thanks for your response sir, but i saw that Laravel Sanctum was advised only for "Single Page Application".
So I don't really know if I can use it for my application.
EDIT : Plus, it seems that Laravel Sanctum work only for Laravel 7.x and 8.x and one my applications is on Laravel 6.x
if you create api routes in the api.php file then they will be stateless and csrf is not possible
Typically you would not use csrf on api requests because you are not sending the client a form
Thanks for your response sir.
But how can you "protect" these routes using csrf protection logic then ?
typically you should not need to
each request to your api carries its own authentication bearer token and csrf is not a concern
@Snapey Hey, i'm working on a project with different user types each in different tables with laravel API for backend and react for frontend (on the same domain). On login I issue a token and save it as http only cookie that i later use for auth. Is it enough or csrf protection is needed?
@peuf if you are dealing with both back end and front end, why not a regular web app?
Normally in an api you would have nothing to do with the front end. The user or organization using the api designs their front end. Not counting if it's a native mobile app.
You give instructions on how the api data is retrieved and paginated.
Probably around 90% of folks dealing with an api I've observed that a regular web app would be better suited.
As far as the csrf, it depends on the back end and sometimes only for initial login. An initial login is only to check credentials and retrieve a token or issue one and csrf is generally not used, then the back and forth communication is token based. Either a cookie or local storage is used.
Besides here, there are some decent youtube videos on passport and sanctum which explains this stuff in detail.
I am more familiar with the key and secret type API's.
Edit:
Many api's also have regular direct to the website login for updating or adding data. So some are regular websites and api's.
But there are hundreds of ways api's are done.
To me, an api should only be used when necessary, like a doctor getting lab results from an outside lab, weather is another example.
@jlrdw I'm working with API because there will be a mobile app in the near future using the same backend.
@vincent15000 React js
@peuf If your application works with Laravel 6.x, I suggest you to upgrade the application to a more recent version.
Please or to participate in this conversation.