diff --git a/contrib/docs/tutorials/authenticate-api-requests.md b/contrib/docs/tutorials/authenticate-api-requests.md index 9f651ddd1a..803a6babc7 100644 --- a/contrib/docs/tutorials/authenticate-api-requests.md +++ b/contrib/docs/tutorials/authenticate-api-requests.md @@ -129,8 +129,12 @@ function msUntilExpiry(token: string): number { // Calls the specified url regularly using an auth token to set a token cookie // to authorize regular HTTP requests when loading techdocs -async function setTokenCookie(url: string, getIdToken: () => Promise) { - const token = await getIdToken(); +async function setTokenCookie(url: string, identityApi: IdentityApi) { + const { token } = await identityApi.getCredentials(); + if (!token) { + return; + } + await fetch(url, { mode: 'cors', credentials: 'include', @@ -138,11 +142,12 @@ async function setTokenCookie(url: string, getIdToken: () => Promise) { Authorization: `Bearer ${token}`, }, }); + // Call this function again a few minutes before the token expires const ms = msUntilExpiry(token) - 4 * 60 * 1000; setTimeout( () => { - setTokenCookie(url, getIdToken); + setTokenCookie(url, identityApi); }, ms > 0 ? ms : 10000, ); @@ -160,16 +165,13 @@ const app = createApp({ providers={['guest', 'custom', ...providers]} title="Select a sign-in method" align="center" - onResult={async result => { - // When logged in, set a token cookie - if (typeof result.getIdToken !== 'undefined') { - setTokenCookie( - await discoveryApi.getBaseUrl('cookie'), - result.getIdToken, - ); - } - // Forward results - props.onResult(result); + onSignInSuccess={async (identityApi: IdentityApi) => { + setTokenCookie( + await discoveryApi.getBaseUrl('cookie'), + identityApi, + ); + + props.onSignInSuccess(identityApi); }} /> );