0

Hope all is well.

I' m trying to implement SignalR in my Blazor server-side app, which also implements Asp.net core identity. I get the following message when I navigate to the razor page that implements the signalr hub:

HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).

And the following is highlighted in red for exception:

await hubConnection.StartAsync();

Here is my razor page code behind:

private HubConnection hubConnection;

protected override async Task OnInitializedAsync()
{

    hubConnection = new HubConnectionBuilder()
    .WithUrl(NavigationManager.ToAbsoluteUri("/EmployeePresenceStatusHub"))
    .WithAutomaticReconnect()
    .Build();

    hubConnection.On("ReceiveMessage", () =>
    {
        LoadEmployeesPresenceStatus();
        StateHasChanged();//Refresh the component using updated data
    });

    await hubConnection.StartAsync();

}

Here is my hub class:

public class EmpoyeesPresenceStatusHub : Hub
{
    public async Task SendMessage()
    {
        await Clients.All.SendAsync("ReceiveMessage");
    }
}

I've followed the example from here:

Use ASP.NET Core SignalR with Blazor

I'm presuming asp.net core identity feature in my Blazor app is causing this?

Any help most appreciated.

SM1012
  • 31
  • 6
  • Are you using Windows Authentication by any chance? – Lex Apr 22 '21 at 22:14
  • See this answer: https://stackoverflow.com/a/66617648/6152891 Don't use the code... Instead see updated version here: https://github.com/enetstudio/SignalRServerIdentityAuthentication – enet Apr 23 '21 at 00:49

1 Answers1

4

Try Using Cookies to connect to the hub. I am sure if that is ideal but it solved my issue.


Create a cookie provider class

    public class CookieProvider
    {
        public string Cookie { get; set; }
    }

Register this class as a Scoped Service

    buider.Services.AddScoped<CookieProvider>(); //net6.0
    services.AddScoped<CookieProvider>(); //net5.0

Inject the service globaly in _imports.razor


    @inject CookieProvider CookieProviderService

Inside App.razor add a code section with the following

   [Parameter]
   public string Cookie { get; set; }
   protected override Task OnInitializedAsync()
   {
        CookieProviderService.Cookie = Cookie;

        return base.OnInitializedAsync();
   }

Inside _Host.cshtml

@{
    var cookie = 
        HttpContext.Request.Cookies[".AspNetCore.Identity.Application"];

 }

<component type="typeof(App)" param-Cookie="cookie"  render-mode="ServerPrerendered" />

Lastly Create Your Hubconnection

 var container = new CookieContainer();
            var cookie = new Cookie()
            {
                Name = ".AspNetCore.Identity.Application",
                Domain = "localhost",
                Value = CookieProviderService.Cookie
            };
            container.Add(cookie);
            hubConnection = new HubConnectionBuilder()
                            .WithUrl(_navigationManager.ToAbsoluteUri(ChatHub.HubUrl),
                             options =>
                             {
                                 options.Cookies = container;
                             })
                            .WithAutomaticReconnect()

                            .Build();