Open ernsheong opened 7 years ago
(thinking aloud)
Perhaps a more restrictive way is to store the refresh token in a cookie on a specific path, e.g. "/refresh-token" instead of passing it along on every API request unnecessarily. Drawback is that an additional API request is required on token expiry to do the renewing.
I agree, it's a bit redundant. And I think you've correctly identified the downside of not sending them both (namely that a second request will need to be made to a refresh token refresh endpoint). Depending on use case, a solution like that could certainly be beneficial, albeit more complex.
Bit late to the responses.. but what you can do is send both access and refresh tokens back as httpOnly cookies (secure too for production use). Set the path for the refresh token to something like /token and the endpoint of /token/check could be set up to check that a refresh token is valid (e.g. a user reloads a web page OR comes to a web page from a bookmark, send to verify the token is valid) and /token/refresh would be used via POST to create a new access token (and optionally a new refresh token if wanted). If the refresh token (on /token/check) is invalid, the web app would show the login screen. All other API calls from the web app would only send the access token which has a path of /.
With this way of doing things, you don't have to store either access or refresh token in local storage. Just make sure your fetch() or axios() or whatever you are using to submit API requests sets the correct options. For example using HTML fetch call you would set it up like:
const ri = {
headers: _headers,
method: mthd,
mode: 'cors',
cache: 'no-cache',
credentials: 'same-origin', // include, *same-origin, omit (same-origin for cookies...)
body: mthd !== 'GET' ? JSON.stringify(body) : null
};
try {
const res = await fetch(api_url_path, ri);
const responseOK = res && res.ok;
if (responseOK) {
const data = await res.json();
return data;
} else {
return res;
}
} catch(error) {
return error;
}
I find it a bit odd that BOTH access and refresh tokens are submitted with every API request in a cookie.
This seems reasonable, given the web consensus is that local storage is not trustworthy.
So question is, can we do better?