Search code examples
javascriptnode.jscookiesjwttoken

Where do I store the refresh token and access token and how do I use it?


i can't easily decide how to receive the refresh token and access token from the back-end and where to store it.

the authentication process I understand is as follows.

  1. XSS can be defended with cookies.
  2. using cookies is vulnerable to CSRF.
  3. however, in the case of cookie, it can be stolen as 'document.cookie'. So, use the 'httponly' option to prevent access from javascript.
  4. cookie is always included in header when making http request, so it is vulnerable to CSRF. So, when logging in, 'refresh token' and 'access token' are created in the back-end, stored in the DB, and returned to the client.
  5. request an api using an access token, and if it expires, update it using a refresh token.

as I refer to many articles, it is said that XSS is to be blocked with cookies and CSRF is to be protected with refresh tokens and access tokens.

and in the case of refresh token, it is stored in webStorage.

however, in order to prevent XSS, it seems that in the case of access tokens, cookies should be used to protect them (+ httponly applied), and in the case of refresh tokens, it seems that they should be stored in the client.

if the refresh token is sent in a cookie with the httponly option, isn't it accessible from the client?


in conclusion...

in the back-end server, should the access token be sent as a cookie and the refresh token included in the body?

Any ideas would be appreciated.


Solution

  • The tokens are usually sent back in the body of the response. This way your frontend app can easily read them and store wherever needed. Usually storing them in memory should be enough (in a variable or state of your app, etc.). When the user refreshes the page they will have to log in again, but that should not be a problem if the Authorization Server supports things like "remember me". If you're using an OpenID Connect-compliant Authorization Server, then you can perform a silent login - so obtain tokens without the need of redirecting the user anywhere.

    If you store your tokens in a http-only cookie then your app will not have access to them, so you won't be able to call any APIs from your app. I think this is not what you're trying to achieve.

    Keeping the tokens in memory could help you be a bit more safe from XSS attacks, but you will never be 100% secure. Have a look at this talk: https://pragmaticwebsecurity.com/talks/xssoauth.html where it is explained. In fact the only way to be sure that an XSS attack can't steal your tokens is to keep the tokens in a backend app, not in the browser.