Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I add custom headers to SignalR's Typescript client?

I am trying to pass a bearer token in the header to authorize client connections. The SignalR hub authorizes client by grabbing the bearer token from the header. I cannot modify the SingalR hub code to use a query string to get the token, nor can I use the built-in JWT token functionality.

How do I add a custom header to the SignalR typescript client?

The only thing I can think to do is override the HttpClient in to add the header however I am not sure if this is possible or how to do this.

I am using @microsoft/signalr in Angular 8 and the latest @microsoft/signalr package.

like image 379
Metallic Avocado Avatar asked Dec 08 '22 11:12

Metallic Avocado


2 Answers

You can add a custom HttpClient in the options when building the connection.

It would look something like this:

class CustomHttpClient extends DefaultHttpClient {
  public send(request: HttpRequest): Promise<HttpResponse> {
    request.headers = { ...request.headers, "customHeader": "value" };
    return super.send(request);
  }
}

let hubConnection = new HubConnectionBuilder()
    .withUrl(url, { httpClient: new CustomHttpClient() })
    .build();

It is possible to inherit from the DefaultHttpClient and in your send you call the DefaultHttpClient's send so you don't need to implement the Http calls yourself.

First class support has been implemented in 5.0 or higher of the @microsoft/signalr package via the headers property on IHttpConnectionOptions, see https://github.com/dotnet/aspnetcore/issues/14588 for the resolved GitHub issue.

like image 130
Brennan Avatar answered Mar 07 '23 03:03

Brennan


If this is just to pass a bearer token then no need to do custom headers, to pass an access token you can use withUrl overload that takes IHttpConnectionOptions, this interface has accessTokenFactory that can be used like this:

yourAuthServicePromise.then(
  (data) => {
    if (data.['result']['accessToken']) {
      this.hubConnection = new signalR.HubConnectionBuilder()
        .withUrl('https://SIGNALR_SERVER_HUB_URL', {
          accessTokenFactory: () => {
            return data.['result']['accessToken'];
          }
        } as signalR.IHttpConnectionOptions)
        .build();
      this.hubConnection.start()
    }
  }
);

Don't forget to enable cors policy in the hub Server in order to allow the JS client origin

like image 28
Ali Abdulla Avatar answered Mar 07 '23 03:03

Ali Abdulla