Search code examples
c#asp.net-coresignalr-hub

401 with Blazor WASM + SignalR on API connection


  • Server A hosts a Blazor WASM app.
  • Server B hosts an API.
  • All authentication is Windows Auth.

The API provides data to the WASM app, everything works as expected. But what does not work is the SignalR connection I try to setup, from WASM to the API. 401 Unauthorized.

enter image description here

From the IIS log, I can conclude that the negotiate POST request to establish the connection doesnt send user credentials (precise log error is 401 2 5). But setting "UseDefaultCredentials = true" in the connection builder throws a "platform not supproted" exception.

Code for connection setup:

connection = new HubConnectionBuilder()
    .WithUrl($"{Program.AppConfig["http:baseAddress"]}someURL", options =>
    {    
         //options.UseDefaultCredentials = true; <- throws
    }) 
    .AddJsonProtocol(options => 
    {
        options.PayloadSerializerOptions.PropertyNamingPolicy = null;   
        options.PayloadSerializerOptions.ReferenceHandler = ReferenceHandler.Preserve;
        options.PayloadSerializerOptions.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull;
    })
    .ConfigureLogging(x => x.SetMinimumLevel(LogLevel.Trace))
    .Build();

Setting or removing [Authorize] attribute on the API code for the hub doesnt do anything, as the IIS is already refusing the connection, not the API.

Is there any way to send credentials or is SignalR intended to not work on Blazor WASM apps? If so, are there alternatives? Bearer token auth? It works on a development environment where API and app both run on the same machine.

I tried to set different authentication values, like allow annonymous. Tinkered with the options of SignalR connection.

Google couldn't provide concise results on the issue.


Solution

  • If anyone finds this and has the same issue, I was not able to fix it properly. Instead, I use JavaScript-SignalR to establish the connection and JSInterop to provide the data to the Blazor app.

    I'm not sure if this is correct, but I've read that Blazor WASM simply isnt capable of providing user credentials to SignalR. Which is weird but fits with the PlatformNotSupported exception I got.

    Edit: I stumbled upon this article which is a way better solution for what I was trying to do.