Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
537 views
in Technique[技术] by (71.8m points)

c# - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...