ASP.NET Core and SignalR Authentication (with the JavaScript client)
Websocket protocol in the browser does not support HTTP Headers. If you are using the SignalR JavaScript client you’ll realise that the access token is passed as a query parameter.
If your project already has Authentication enabled then you’ll notice that the protocol will 401, and fall back on XHR polling.
To solve this you need a custom middleware in your ASP.NET Core project that swaps your `access_token` found in your query parameter and adds it as an Authorization header. This middleware should run before app.UseAuthentication()
Your middleware should look like this:
Note: that this middleware assumes that your SignalR hub is in the path starts with /hub
else it will skip it.
Use it like this:
app.UseMiddleware<WebSocketsMiddleware>();app.UseAuthentication();
Lastly ensure your client’s connection is setup to pass the token like this:
this.connection = new HubConnectionBuilder()
.withUrl('https://YOUR_HUB_URL_HERE/hub', {
accessTokenFactory: () => 'YOUR ACCESS TOKEN TOKEN HERE'
})
.build();
SignalR client: https://www.npmjs.com/package/@aspnet/signalr
That’s it. You should be able to authenticate properly and get the correct user claims when using the Authorize attribute inside your hub.
[Authorize]
public class YourHub : Hub {
...
}
Discussion around the issue and alternative approaches here: https://github.com/aspnet/SignalR/issues/130
Enjoy!
Need more help? You can reach me at alani.co.nz.