Can I prevent CSRF attacks by using localstorage/sessionstorage?
https://softwareengineering.stackexchange.com/questions/314412
Question
I have a front/back applications that needs to be logged in to be used. When I log in (by means of the front-end app sending a request to the back end), what I do is not sending a cookie, but a JSON
with a token in it. The latter will be stored by the front end app in a sessionstorage
and each time it will interact with the back end it will send a request along with the token stored in the sessionstorage
. The back end will verify the validity of the token.
Do you think this solution is CSRF safe? Do you see any other vulnerabilities I'm not considering/ignoring?
Solution
It's certainly safer than using a cookie when it comes to CSRF, but it is less safe when it comes to XSS, because session storage can be read from javascript, while http-only cookies cannot.
So it depends on how confident you are about your protection against XSS.
If you do go for this approach, I would suggest using the Authorization header with the Bearer scheme.
Authorization: Bearer <token>
Other things to keep in mind:
- Session storage isn't shared between tabs.
- You can't use this method for images that require authentication. For those you could still use a cookie (just make sure you ignore the cookie for all other endpoints and possibly limit the path of the cookie to a path under which only images are found)