Getting SignalR unauthorized error in ReactJS

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. signalr connection 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 a code sample for the 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

What you wrote is correct, you don’t have an access token so you are getting Unauthorized error!

I don’t know how your complete app works but I guess you have a Login screen, why don’t you get access token on login screen and store it into local storage?
If you have only this screen you can put hubConnection in getUrl method, add it to state and use it from state. I’m not sure will it work!

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.