-
Notifications
You must be signed in to change notification settings - Fork 0
feat: Implement token renewal service and integrate with authenticati… #14
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,32 @@ | ||
| import { useEffect } from 'react'; | ||
| import { useIsAuthenticated } from '@azure/msal-react'; | ||
| import { tokenRenewalService } from '../services/tokenRenewalService'; | ||
| import { USE_MSAL_AUTH } from '../app.config'; | ||
|
|
||
| /** | ||
| * Custom hook to manage token renewal for authenticated users | ||
| * Automatically starts/stops the renewal service based on authentication state | ||
| */ | ||
| export const useTokenRenewal = (): void => { | ||
| const isAuthenticated = useIsAuthenticated(); | ||
|
|
||
| useEffect(() => { | ||
| // Only manage token renewal when using MSAL auth | ||
| if (!USE_MSAL_AUTH) { | ||
| return; | ||
| } | ||
|
|
||
| if (isAuthenticated) { | ||
| console.log('User authenticated, starting token renewal service'); | ||
| tokenRenewalService.start(); | ||
| } else { | ||
| console.log('User not authenticated, stopping token renewal service'); | ||
| tokenRenewalService.stop(); | ||
| } | ||
|
|
||
| // Cleanup on unmount | ||
| return () => { | ||
| tokenRenewalService.stop(); | ||
| }; | ||
| }, [isAuthenticated]); | ||
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| import { msalInstance, loginRequest } from '../authConfig'; | ||
| import { InteractionRequiredAuthError } from '@azure/msal-browser'; | ||
|
|
||
| class TokenRenewalService { | ||
| private renewalInterval: NodeJS.Timeout | null = null; | ||
| private isRenewing = false; | ||
| private readonly RENEWAL_INTERVAL = 30 * 60 * 1000; // 30 minutes | ||
| /** | ||
| * Start the token renewal service | ||
| */ | ||
| public start(): void { | ||
| if (this.renewalInterval) { | ||
| this.stop(); // Clear existing interval | ||
| } | ||
|
|
||
| console.log('Starting token renewal service...'); | ||
|
|
||
| // Initial token check | ||
| this.renewTokenIfNeeded(); | ||
|
|
||
| // Set up periodic renewal | ||
| this.renewalInterval = setInterval(() => { | ||
| this.renewTokenIfNeeded(); | ||
| }, this.RENEWAL_INTERVAL); | ||
| } | ||
|
|
||
| /** | ||
| * Stop the token renewal service | ||
| */ | ||
| public stop(): void { | ||
| if (this.renewalInterval) { | ||
| clearInterval(this.renewalInterval); | ||
| this.renewalInterval = null; | ||
| console.log('Token renewal service stopped'); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Manually trigger token renewal | ||
| */ | ||
| public async renewToken(): Promise<boolean> { | ||
| return this.renewTokenIfNeeded(); | ||
| } | ||
|
|
||
| /** | ||
| * Check if token needs renewal and renew if necessary | ||
| */ | ||
| private async renewTokenIfNeeded(): Promise<boolean> { | ||
| if (this.isRenewing) { | ||
| console.log('Token renewal already in progress, skipping...'); | ||
| return false; | ||
| } | ||
|
|
||
| try { | ||
| this.isRenewing = true; | ||
|
|
||
| const accounts = msalInstance.getAllAccounts(); | ||
| if (accounts.length === 0) { | ||
| console.log('No accounts found, cannot renew token'); | ||
| return false; | ||
| } | ||
|
|
||
| const account = accounts[0]; | ||
|
|
||
| // Check if token is close to expiry | ||
| if (!this.isTokenNearExpiry(account)) { | ||
| console.log('Token is still valid, no renewal needed'); | ||
| return true; | ||
| } | ||
|
|
||
| console.log('Token is near expiry, attempting silent renewal...'); | ||
|
|
||
| // Attempt silent token renewal | ||
| await msalInstance.acquireTokenSilent({ | ||
| ...loginRequest, | ||
| account: account, | ||
| forceRefresh: true, // Force refresh to get new token | ||
| }); | ||
|
|
||
| console.log('Token renewed successfully via silent request'); | ||
| return true; | ||
|
|
||
| } catch (error) { | ||
| console.warn('Silent token renewal failed:', error); | ||
|
|
||
| if (error instanceof InteractionRequiredAuthError) { | ||
| console.log('Interactive authentication required - user will need to sign in again on next request'); | ||
| // Don't trigger popup automatically as it might be disruptive | ||
| // Let the user-triggered request handle the interactive flow | ||
| } | ||
|
|
||
| return false; | ||
| } finally { | ||
| this.isRenewing = false; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Check if the current token is near expiry | ||
| */ | ||
| private isTokenNearExpiry(_account: any): boolean { | ||
| // Always attempt renewal for proactive refreshing | ||
| // MSAL handles token expiry checks internally, so we'll rely on forceRefresh | ||
| return true; | ||
| } | ||
|
|
||
| /** | ||
| * Get the renewal interval in milliseconds | ||
| */ | ||
| public getRenewalInterval(): number { | ||
| return this.RENEWAL_INTERVAL; | ||
| } | ||
|
|
||
| /** | ||
| * Check if the service is currently running | ||
| */ | ||
| public isRunning(): boolean { | ||
| return this.renewalInterval !== null; | ||
| } | ||
| } | ||
|
|
||
| // Export a singleton instance | ||
| export const tokenRenewalService = new TokenRenewalService(); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -2,23 +2,34 @@ import { SavedQuery } from '../types'; | |||||
| import { msalInstance, loginRequest } from '../authConfig'; | ||||||
| import { USE_MSAL_AUTH, API_BASE_URL } from '../app.config'; | ||||||
| import { mockDelay, mockSavedQueries } from './mockData'; | ||||||
| import { getAuthErrorMessage, isAuthenticationExpiredError } from '../utils/authErrorHandler'; | ||||||
| import { getAuthErrorMessage, isAuthenticationExpiredError, isRecoverableAuthError } from '../utils/authErrorHandler'; | ||||||
|
|
||||||
| const getAccessToken = async (): Promise<string> => { | ||||||
| try { | ||||||
| const accounts = msalInstance.getAllAccounts(); | ||||||
| if (accounts.length === 0) { | ||||||
| throw new Error("No signed-in user found."); | ||||||
| } | ||||||
|
|
||||||
| // Try silent token acquisition first | ||||||
| const response = await msalInstance.acquireTokenSilent({ | ||||||
| ...loginRequest, | ||||||
| account: accounts[0], | ||||||
| }); | ||||||
| return response.accessToken; | ||||||
| } catch (error) { | ||||||
| // Handle authentication errors with user-friendly messages | ||||||
| if (isAuthenticationExpiredError(error)) { | ||||||
| throw new Error(getAuthErrorMessage(error)); | ||||||
| // If silent token acquisition fails, check if we can recover with interactive auth | ||||||
| if (isRecoverableAuthError(error) || isAuthenticationExpiredError(error)) { | ||||||
| try { | ||||||
| console.log('Silent token acquisition failed, attempting popup refresh...'); | ||||||
| // Try popup for token refresh | ||||||
| const response = await msalInstance.acquireTokenPopup(loginRequest); | ||||||
| return response.accessToken; | ||||||
| } catch (popupError) { | ||||||
| console.error('Popup token refresh also failed:', popupError); | ||||||
| // Only after both silent and popup fail, throw the user-friendly error | ||||||
| throw new Error(getAuthErrorMessage(error)); | ||||||
|
||||||
| throw new Error(getAuthErrorMessage(error)); | |
| throw new Error(getAuthErrorMessage(popupError)); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The
isTokenNearExpirymethod always returnstrue, making it redundant. Consider removing this method and directly calling the renewal logic, or implement actual token expiry checking logic if needed.