📎 Webclip
Today's rabbit hole: securing JWTs for authentication, httpOnly cookies, CSRF tokens, secrets & more
The post follows a debugging journey through JWT storage and protection in a React and Express setup. It argues for storing the token in an httpOnly cookie rather than localStorage, using a separate client-visible cookie to detect login state, and handling logout by overwriting the server cookie and clearing the visible flag.
Reading notes#
- localStorage is described as unsafe because third-party scripts can access stored tokens.
- an httpOnly cookie is presented as the safer place to store the JWT because browser JavaScript cannot read or write it.
- the login endpoint generates the JWT and saves it with
res.cookie('token', token, { httpOnly: true }). document.cookiecan read the cookie whenhttpOnlyis false, but not when it is true.- browser memory is mentioned as a safe option, but the token is lost on refresh and login must happen again.
- a second cookie, with
httpOnly: false, is used only to show whether the user is logged in. - route protection is done with a
PrivateRoutethat checksisLoggedIn === 'true'and redirects to/loginotherwise. - the author uses
js-cookieto read cookies in React. - logout removes the token by sending a server cookie with the same name and a dummy value, and sets
isLoggedInto false. - the post frames CSRF as a risk for authenticated requests because browser cookies are sent automatically.
- it mentions CORS policy, CSRF tokens, and SameSite cookies as defenses.
csurfis used to generate a CSRF token and a secret, with the token sent to the client and the secret stored in a cookie.- the client stores the token in an
X-CSRF-Tokenheader for later AJAX requests. - the author uses Axios
withCredentials: truein development and relies on credentials handling and domain settings in production. csurfis described as validating the token against the secret and throwing an error if verification fails.- both Ryan Chenkie and Harleen Mann are cited as saying that in-memory JWT storage with refresh tokens is the safest approach.
