I can see that there is an option in HubConnection to pass parameters through url request from client. Is there any way to pass specific token through http headers from JS or .NET clients?
In standard web APIs, bearer tokens are sent in an HTTP header. However, SignalR is unable to set these headers in browsers when using some transports. When using WebSockets and Server-Sent Events, the token is transmitted as a query string parameter.
There is no easy way to set HTTP headers for SignalR requests using the JS or .NET client, but you can add parameters to the query string that will be sent as part of each SignalR request: $.connection.hub.qs = { "token" : tokenValue }; $.connection.hub.start ().done (function () { /* ...
The access token function you provide is called before every HTTP request made by SignalR. If you need to renew the token in order to keep the connection active (because it may expire during the connection), do so from within this function and return the updated token.
If the user is logged in to your app, the SignalR connection automatically inherits this authentication. Cookies are a browser-specific way to send access tokens, but non-browser clients can send them. When using the .NET Client, the Cookies property can be configured in the .WithUrl call to provide a cookie.
There is no easy way to set HTTP headers for SignalR requests using the JS or .NET client, but you can add parameters to the query string that will be sent as part of each SignalR request:
JS Client
$.connection.hub.qs = { "token" : tokenValue }; $.connection.hub.start().done(function() { /* ... */ });
.NET Client
var connection = new HubConnection("http://foo/", new Dictionary<string, string> { { "token", tokenValue } });
Inside a Hub you can access the community name through the Context:
Context.QueryString["token"]
You can add to the query string when making persistent connections as well.
EDIT: It is now possible to set headers on the .NET SignalR client as pointed out by some of the commenters.
Setting Headers on the .NET Client
var connection = new HubConnection("http://foo/"); connection.Headers.Add("token", tokenValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With