2
votes

I create a realtime connection via SignalR From client(angular 9) and server(asp.net core 3.1) and Authorize hub by JWT Token such as below code :

 private createConnection() {
      this.hubConnection = new HubConnectionBuilder().withUrl(`${this.appConfig.hubEndpoint}/Hubs`,
        { accessTokenFactory: () => jwtToken })
        .withAutomaticReconnect()
        .build();
  }

  private startConnection(): void {
    this.hubConnection
      .start()
      .then(() => {
        this.connectionIsEstablished = true;
        this.connectionEstablished.emit(true);
      })
      .catch(err => {
        console.log('Error while establishing connection, retrying...');
      });
  }

this works fine until the token expired. According to my research, after receiving the new token with the refresh token, the previous connection should be stopped and a new connection should be created with the new token. Now I want to know how should I do this? Do I have to constantly check the token? Or should this be addressed by sending each request to the server?

2
did you find a way?Kardon63
@Kardon63 did you find a way too ? xDMehdi Benmoha
@MehdiBenmoha On the close event you can check if the error string contains unauthorized and then you can restart the connection, didn't implement it yet but this is how I think it should be doneKardon63
I am giving it a try.. will update you if I get it workingMehdi Benmoha
@Kardon63 the onclose event is triggered but the string doesn't contain unauthorized, the listener gets an undefined value. It was also very hard for me to renew the connection because I am using an async call to get the token and I am wrapping the whole system with rxJS, so the quick and dirty fix was to reload the page when a disconnected event is received, while also setting aggressive delays for automatic reconnects.Mehdi Benmoha

2 Answers

0
votes

When the token will expire the connection will be droped by the server and you will have the error on the server side. I believe is the 405 error code Method now allowed that you will get.

So what you need is catch this token expiration error and drop the connection so you can start a new one with the new token.

0
votes

What did work for me, it's a QUICK AND DIRTY fix, was to reload the page on close events:

this.hubConnection.onclose(() =>{
  window.location.reload()
})

Explanation

I am wrapping the connection process with RxJS, so a better fix for my case is to throw an error instead of reloading the page and catch it with retryWhen operator. But as this is a hard bug (need to wait 1h for the token to expire, and locally the emulator doesnt care about tokens...), I just prefered to go with this temporary solution.