Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix: Refresh access_token if expired #24

Merged
merged 9 commits into from Nov 5, 2020

retry fetch properly if recieved 401

  • Loading branch information
fcjr committed Nov 5, 2020
commit 5161065f357aa453f95789d86f612615104ffc79
@@ -53,16 +53,14 @@ class TokenPool {
pretokens.push({ token, blindFactor });
}

const response = await fetch(`${API_BASE_URL}/tokens/new`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
blindTokens,
}),
});
let response = await this._fetchNewTokens(accessToken, blindTokens);
if (response.status === 401) {
// try to refresh token and try again if authorization failed
// as the token technically could have expired by the time the request
// arives
const accessToken = await AccessToken.get();
response = await this._fetchNewTokens(accessToken, blindTokens);
}
if (response.ok) {
const { tokens } = await response.json();
const res = [];
@@ -83,9 +81,19 @@ class TokenPool {
});
console.warn(`Adding ${res.length} tokens to acquired pool`);
this.tokens.push(...res);
} else if (response.status === 401){
This conversation was marked as resolved by fcjr

This comment has been minimized.

@sammacbeth

sammacbeth Nov 5, 2020
Contributor

A 401 from the token endpoint means that the access token is expired. Don't we also need to handle this case by forcing a refresh? Cookies are not always deleted immediately on expiry, so we could exhaust our tokens before the cookie listener is called. It would be possible to trigger it by manually deleting the cookie with the cookie API.

This comment has been minimized.

@fcjr

fcjr Nov 5, 2020
Author Member

Ah yeah, added this back

// refresh the access token. This will call generateTokens if the refresh is successful
AccessToken.refresh();
}
}

async _fetchNewTokens(accessToken, blindTokens) {
return fetch(`${API_BASE_URL}/tokens/new`, {
method: 'POST',
headers: {
'Authorization': `Bearer ${accessToken}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
blindTokens,
}),
});
}
}
ProTip! Use n and p to navigate between commits in a pull request.