full-stack-fastapi-template
full-stack-fastapi-template copied to clipboard
Use of localStorage for JWT tokens insecure?
Reviewing the frontend code, I saw that it appears the Vuex store saves the JWT tokens in localStorage, against common security recommendations. Although this is just an example project, it's never a good idea to promote bad security practices that find their way into production applications, especially when teaching new developers the "right" way to build Single Page Applications. Would it be possible instead to re-architect this application to use e.g. HttpOnly cookies?
so I'm kinda curious @danjac how would you do this then? Most articles and even code you look at use this same type of setup with vuex typically storing the token. I thought if you had enough form validation in your frontend a XSS attempt would be pretty low or no? I'm following this as I'm setting up a production level app atm sorta based off this and I'm kinda curious the impact of using the vuex store with proper form validation on any inputs.
For a browser frontend I would stick to server HttpOnly cookies that are not accessible to your JS code at all, combined with some form of CSRF protection for POST and other write requests. The index page that loads your application is rendered by your server, which includes a JSON script tag containing all the data you need to hydrate your Vuex store - for example the authenticated user.
I think the reason so many articles sidestep this issue is either just pure ignorance - every other article does it, so why not me? Assumption that Vue/React/etc will automatically handle XSS (they do to some extent, but can you ensure some obscure dependency from npm isn't doing something evil? And what if you want to render some user data as html, for example with some markdown editor?) and just plain convenience/laziness - it's easy to just throw a token into localStorage without further explanation of the tradeoffs that might confuse readers.
I found this: https://github.com/cthwaite/fastapi-jwt-cookies And this: https://github.com/tiangolo/fastapi/issues/480
I think a better option is to save the token in a samtesite=Strict cookie
The Strict value will prevent the cookie from being sent by the browser to the target site in all cross-site browsing context, even when following a regular link.
afaik this will prevent csrf and xss attacks
@danjac
Assumption that Vue/React/etc will automatically handle XSS (they do to some extent, but can you ensure some obscure dependency from npm isn't doing something evil?
HttpOnly is also ineffective if vulnerable to XSS attacks. HttpOnly is effective against "cookie stealing" attacks, but hackers do not want to steal cookies. If DOM manipulation is possible, other attacks (e.g., changing passwords) are still possible with XMLHttpRequest, because cookies are granted automatically.