You should use httpOnly
cookie to prevent access from JS, (with xss attach you can execute JS on other users session).
My suggestion (which us base on The Ultimate Guide to handling JWTs on frontend clients) is to use 2 kind of tokens:
- Refresh Token - stored on
httpOnly
cookie, is used to update the accessToken only, it is valid for long period (no recommended longer than 1 day)
- Access Token - stored in memory, attached to each request that needs auth. valid for short period of time (10 mins).
The idea works like this:
- User logins, your server validates the credentials and generate an
httpOnly
cookie with the refreshToken
and returns as a response the accessToken
.
- Your client app sores the accessToken on some class instance (when used with
Axios
you can attach it as base Authorization header to all requests).
- When your app makes a request, it adds the AccessToken as the Authorization header, if the AccessToken expires your api will return 403 UnAuthorized, your client app makes a request to special end point
/auth/token
with the httpOnly cookie which holds refreshToken, this end point validates the refreshToken, and returns a new accessToken with expiration time of 10mins (which your client app updates the base Auth header with), then your app can retry the previous failed request with the new accessToken.
With this method, there is no access to any kind of tokens from outside of your app.
The refreshToken
is not accessible at all to your js and the accessToken is held in memory, only if your app has some flaw it will be exposed, and even if the attacker stole it, it is valid only for 10 mins (without the ability to get a new one because it doesn't have the refreshToken)
For more details read the article I've added.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…