Middle+
Where is the correct place to store the refresh token on the client side?
sobes.tech AI
Answer from AI
A refresh token is a sensitive element that allows obtaining a new access token without re-authenticating the user. It should be stored on the client as securely as possible to minimize the risk of theft.
Proper storage approaches:
- HttpOnly Secure Cookie — the safest method. Cookies with HttpOnly and Secure flags are inaccessible via JavaScript and are transmitted only over HTTPS, reducing the risk of XSS and MITM attacks.
- In application memory — if the application is SPA, you can store the refresh token in memory (e.g., in a variable), but then the token is lost upon page refresh.
What not to do:
- Do not store the refresh token in localStorage or sessionStorage, as they are accessible via JavaScript and vulnerable to XSS.
Example of setting an HttpOnly cookie on a Python (Flask) server:
from flask import Flask, make_response
app = Flask(__name__)
@app.route('/set_refresh_token')
def set_refresh_token():
resp = make_response('Refresh token set')
resp.set_cookie('refresh_token', 'your_refresh_token_value', httponly=True, secure=True, samesite='Strict')
return resp
Thus, the refresh token is stored in a protected cookie and is inaccessible to client-side scripts.