Skip to content

Commit a5e1fbb

Browse files
committed
fix(api-graphql): trigger WebSocket reconnection on auth errors
When subscriptions receive authentication errors (token expired, unauthorized, etc.), close the WebSocket connection to force reconnection with fresh auth tokens. This ensures subscriptions resume after extended idle periods or device sleep/wake cycles. Fixes #12954
1 parent a520acf commit a5e1fbb

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

  • packages/api-graphql/src/Providers/AWSWebSocketProvider

packages/api-graphql/src/Providers/AWSWebSocketProvider/index.ts

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -701,17 +701,44 @@ export abstract class AWSWebSocketProvider {
701701
});
702702

703703
let errorMessage = JSON.stringify(payload ?? data);
704+
let isAuthError = false;
704705

705706
if (type === MESSAGE_TYPES.EVENT_SUBSCRIBE_ERROR) {
706707
const { errors } = JSON.parse(String(message.data));
707708
if (Array.isArray(errors) && errors.length > 0) {
708709
const error = errors[0];
709710
errorMessage = `${error.errorType}: ${error.message}`;
711+
// Check if this is an authentication/authorization error
712+
isAuthError =
713+
error.errorType === 'UnauthorizedException' ||
714+
error.errorType === 'Unauthorized';
710715
}
711716
}
712717

718+
// Also check for auth errors in the error message
719+
isAuthError =
720+
isAuthError ||
721+
errorMessage.includes('UnauthorizedException') ||
722+
errorMessage.includes('Unauthorized') ||
723+
errorMessage.includes('Token expired') ||
724+
errorMessage.includes('NotAuthorizedException') ||
725+
errorMessage.includes('401') ||
726+
errorMessage.includes('403');
727+
713728
this.logger.debug(`${CONTROL_MSG.CONNECTION_FAILED}: ${errorMessage}`);
714729

730+
// If it's an auth error, trigger reconnection to refresh tokens
731+
if (isAuthError && this.awsRealTimeSocket) {
732+
this.logger.debug(
733+
'Subscription failed due to auth error, closing WebSocket to trigger reconnection with fresh tokens',
734+
);
735+
// Close the WebSocket connection which will trigger reconnection
736+
// The connectionStateMonitor will detect the closed connection and since
737+
// intendedConnectionState is still 'connected', it will trigger ConnectionDisrupted
738+
// which causes the ReconnectionMonitor to reconnect with fresh tokens
739+
this.awsRealTimeSocket.close(1000, 'Auth error - reconnecting');
740+
}
741+
715742
observer.error({
716743
errors: [
717744
{

0 commit comments

Comments
 (0)