{"record":{"id":"e534a6921eaf09db","repo":"dotnet/aspnetcore","slug":"cannot-refresh-authentication-when-the-connection","errorCode":null,"errorMessage":"Cannot refresh authentication when the connection is not active.","messagePattern":"Cannot refresh authentication when the connection is not active\\.","errorType":"exception","errorClass":"Error","httpStatus":null,"severity":"error","filePath":"src/SignalR/clients/ts/signalr/src/HubConnection.ts","lineNumber":620,"sourceCode":"    }\n\n    /** Registers a handler that will be invoked when the connection successfully reconnects.\n     *\n     * @param {Function} callback The handler that will be invoked when the connection successfully reconnects.\n     */\n    public onreconnected(callback: (connectionId?: string) => void): void {\n        if (callback) {\n            this._reconnectedCallbacks.push(callback);\n        }\n    }\n\n    /** Refreshes the authentication state for this connection.\n     *\n     * @returns A Promise that resolves with the new server-reported token lifetime in seconds, or undefined when the server does not report one.\n     */\n    public async refreshAuthentication(): Promise<number | undefined> {\n        if (this._connectionState !== HubConnectionState.Connected) {\n            throw new Error(\"Cannot refresh authentication when the connection is not active.\");\n        }\n\n        const authenticationRefreshFeature = this.connection.features.authenticationRefresh as IAuthenticationRefreshFeature | undefined;\n        if (!authenticationRefreshFeature) {\n            throw new Error(\"Authentication refresh is only supported with HTTP-based connections.\");\n        }\n\n        let newTokenLifetimeInSeconds: number | undefined;\n        try {\n            newTokenLifetimeInSeconds = await authenticationRefreshFeature.refreshAuthentication();\n        } catch (e) {\n            await this._invokeAuthenticationRefreshFailed(e);\n            throw e;\n        }\n\n        if (this._connectionState === HubConnectionState.Connected &&\n            this.connection.features.authenticationRefresh === authenticationRefreshFeature &&\n            this._isAutoAuthenticationRefreshEnabled() &&","sourceCodeStart":602,"sourceCodeEnd":638,"githubUrl":"https://github.com/dotnet/aspnetcore/blob/294cab2f9b2e03af6b953820c7ab497c3c8b7ad9/src/SignalR/clients/ts/signalr/src/HubConnection.ts#L602-L638","documentation":"Thrown at HubConnection.ts:620 at the top of `refreshAuthentication()` when the connection state is anything other than Connected. Refreshing authentication requires an active connection to POST the refresh request through; a Disconnected/Connecting/Reconnecting/Disconnecting connection has no valid refresh endpoint.","triggerScenarios":"Calling `hub.refreshAuthentication()` when state is Disconnected (before start or after close), Connecting (during initial handshake), Reconnecting, or Disconnecting. The guard at line 619 fails immediately.","commonSituations":"Auto-refresh timer firing after the connection dropped; calling refresh from a UI button without checking state; refresh triggered in onclose before state fully transitions; reconnect loop calling refresh before the new connection is up.","solutions":["Guard the call: `if (hub.state === HubConnectionState.Connected) await hub.refreshAuthentication();`.","Use the built-in `withAuthenticationRefresh()` builder method which schedules refreshes only on an active connection.","On a Disconnected connection, start() (or re-start) to get a fresh token via the access token factory instead of refresh."],"exampleFix":"// before\nawait hub.refreshAuthentication(); // throws if not connected\n\n// after\nif (hub.state === HubConnectionState.Connected) {\n  await hub.refreshAuthentication();\n} else {\n  await hub.start();\n}","handlingStrategy":"validation","validationCode":"function refreshIfActive(hub) {\n  if (hub.state !== HubConnectionState.Connected) {\n    throw new Error(`Connection not active (state=${hub.state}); refresh ignored`);\n  }\n  return hub.refreshAuthentication();\n}","typeGuard":"function isConnectionActive(hub: HubConnection): boolean {\n  return hub.state === HubConnectionState.Connected;\n}","tryCatchPattern":"try { await hub.refreshAuthentication(); }\ncatch (e) {\n  if (/connection is not active/.test(String(e))) {\n    await hub.start();\n    return;\n  }\n  throw e;\n}","preventionTips":["Guard refreshAuthentication calls with a state check.","Cancel manual refresh timers in onclose.","Prefer the builder's withAuthenticationRefresh auto-scheduling."],"tags":["authentication","refresh","lifecycle","state","validation"],"analyzedSha":"294cab2f9b2e03af6b953820c7ab497c3c8b7ad9","analyzedAt":"2026-08-06T20:08:02.189Z","schemaVersion":2},"datasetVersion":"2026-08-06T23:17:07.152Z"}