Skip to content

Commit

Permalink
Refresh authToken when it expires
Browse files Browse the repository at this point in the history
Access tokens have lifetimes that might end before the user wants to end
their authenticated session. Hence, we need to refresh the user access token
after an expiry detection.

Resolves: #175

Signed-off-by: fenn-cs <[email protected]>
  • Loading branch information
nfebe committed Aug 5, 2023
1 parent eb4fb69 commit 08b69a9
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
1 change: 1 addition & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,4 @@ PERMANENT_API_BASE_PATH=${LOCAL_TEMPORARY_AUTH_TOKEN}
# See https://fusionauth.io/docs/v1/tech/apis/api-keys
FUSION_AUTH_HOST=${FUSION_AUTH_HOST}
FUSION_AUTH_KEY=${FUSION_AUTH_KEY}
FUSION_AUTH_APP_ID=${FUSION_AUTH_APP_ID}
20 changes: 20 additions & 0 deletions src/classes/AuthenticationSession.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,14 @@ enum FusionAuthStatusCode {
export class AuthenticationSession {
public authToken = '';

public refreshToken = '';

public readonly authContext;

private readonly fusionAuthClient;

private readonly fusionAuthAppId = process.env.FUSION_AUTH_APP_ID ?? '';

Check failure on line 24 in src/classes/AuthenticationSession.ts

View workflow job for this annotation

GitHub Actions / run_tests

Multiple spaces found before 'process'

private twoFactorId = '';

private twoFactorMethods: TwoFactorMethod[] = [];
Expand Down Expand Up @@ -46,6 +50,7 @@ export class AuthenticationSession {

private processPasswordResponse([password]: string[]): void {
this.fusionAuthClient.login({
applicationId: this.fusionAuthAppId,
loginId: this.authContext.username,
password,
}).then((clientResponse) => {
Expand All @@ -57,6 +62,7 @@ export class AuthenticationSession {
username: this.authContext.username,
});
this.authToken = clientResponse.response.token;
this.refreshToken = clientResponse.response.refreshToken ?? '';
this.authContext.accept();
return;
}
Expand Down Expand Up @@ -178,4 +184,18 @@ export class AuthenticationSession {
this.authContext.reject();
});
}

private obtainNewAuthTokenUsingRefreshToken(): void {
this.fusionAuthClient.exchangeRefreshTokenForAccessToken(this.refreshToken, '', '', '', '')
.then((clientResponse) => {
this.authToken = clientResponse.response.access_token ?? '';
})
.catch((clientResponse: unknown) => {
const message = isPartialClientResponse(clientResponse)
? clientResponse.exception.message
: '';
logger.warn(`Error obtaining refresh token : ${message}`);
this.authContext.reject();
});
}
}

0 comments on commit 08b69a9

Please sign in to comment.