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

◇◆丶佛笑我妖孽 提交于 2020-05-28 07:34:07

问题


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.


回答1:


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

It would look something like this:

class CustomHttpClient extends HttpClient {
  public send(request: HttpRequest): Promise<HttpResponse> {
    request.headers = { ...request.headers, "customHeader": "value" };
    // ... http call
  }
}

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

It might be 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 is being tracked by https://github.com/dotnet/aspnetcore/issues/14588.




回答2:


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



来源:https://stackoverflow.com/questions/59652214/how-do-i-add-custom-headers-to-signalrs-typescript-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!