Getting SignalR unauthorized error in ReactJS

Vishu 21 Reputation points
2021-09-25T16:34:48.247+00:00

I have created signalR connection in my ReactJS application, whenever i load page for the first time then i get an error "Error: Failed to complete negotiation with the server: Error: Unauthorized" but when i refresh the page again then it start working fine i.e. it get connected properly.

I just want to connect the signalR connection instantly when page load for the first time without the need to refresh it again.

P.S I think connection is trying to connect immediately without waiting for the accessToken to get fetched.
How can i fix this issue in my code?

Here is my code for signalR connection:

 export default class Dashboard extends Component {  
   constructor(props) {  
     super(props)  
     this.state = {  
       signalRURL: 'https://****/?hub=broadcast',  
       accessToken: '',  
       alertData: {}  
     }  
   }  
      
   getURL = () => {  
     return new Promise((resolve, reject) => {  
       return axios({  
         url: 'https://*****/api/SignalRConnection',  
         method: "get",  
         headers: {  
           "content-type": "application/json",  
           "Access-Control-Allow-Origin": "*"  
         },  
       })  
      
         //Get the SignalR connection information which contains Url and Access token,   
         //by calling the SignalRConnection API.  
      
         .then(response => {  
           localStorage.setItem("access_key", response.data.accessToken)  
           console.log("response", response)  
           resolve(response);  
         })  
         .catch(error => {  
           reject(error);  
         });  
     });  
   }  
      
   componentDidMount = () => {  
      
     this.getURL().then(data => {  
       console.log("dataaa", data)  
            
     })  
       .catch(err => {  
         console.log("error", err)  
       })  
      
      
     //Create the Hub connection using SignalR.HubConnectionBuilder.  
     const options = {   
         accessTokenFactory: () => localStorage.getItem("access_key")  
       };   
      
     const hubConnection = new SignalR.HubConnectionBuilder()  
       .withUrl(this.state.signalRURL, options)  
       .configureLogging(SignalR.LogLevel.Information)  
       .build();   
            
     hubConnection.on('notify', data => {   
       this.setState({alertData: data})  
       console.log("state data",this.state.alertData)  
       console.log(data);   
     });   
     hubConnection  
       .start()  
       .catch(  
         error => console.error(error)  
         );   
      
     hubConnection.serverTimeoutInMilliseconds = 6000000;   
     hubConnection.keepAliveIntervalInMilliseconds = 3000000;   
     hubConnection.onclose((error) => {hubConnection.start();   
     console.error(`Something went wrong: ${error}`); });   
        
   }  
   render() {  
     return (  
       <div>  
               
       </div>  
     )  
   }  
 }  

This is the error message i get everytime when i load the page for the first time

135261-image.png

Azure SignalR Service
Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
136 questions
{count} votes

1 answer

Sort by: Most helpful
  1. ajkuma 24,736 Reputation points Microsoft Employee
    2021-09-27T19:02:33.94+00:00

    @Vishu , Thanks for the follow-up.

    I'd also been discussing on this internally, Brennan Conroy from product engineering team has provided suggestions on your GitHub thread. Just copying the answer here; hope you got a chance to look into this, kindly let us know how it goes:

      > // this isn't blocking and you immediately start the hub connection below before getting a response for the token  
      this.getURL().then(data => {  
     console.log("dataaa", data)  
      } )  
    

    . catch(err => {
    console.log("error", err)
    } )

    You aren't waiting for the access token to be fetched before starting the hub connection. By the time you refresh the local storage has been set so it doesn't matter if you start the hub connection early because you already have a token in storage now.