Blazor Server trying SignalR Error 401 (unauthorized) using Windows Authentication

257 views Asked by At

Hey im having a hard time trying to realtime refreshing (without refreshing the page) my Blazor App.

Initial Problem: I have an admin page where admins can change the role of users. The roles are then stored in a database. The user sees the changes only when he reloads the page. Now I was looking for a solution and just found SignalR and tried to integrate it into my project.

Before we get to the problem with SignalR I want to show you how I integrated the Authorization in my Blazor Server Applikation.

I have a Class named UserRoleManager.cs which gets the current AuthenticaitonSate and some data from the currentUser such as RoleId. After that i fill in the ClaimTypes.GroupSid with the roleIds which the User has. To use the AuthenticationStateProvider on every Site I call this Class and Method in my App.razor.

App.razor

@code {
    protected override async Task OnInitializedAsync()
    {
        await UserRoleManager.UpdateUserRole();
    }
}

UserRoleManager.cs

public async Task UpdateUserRole()
        {
            var authState = await _authenticationStateProvider.GetAuthenticationStateAsync();
            var user = authState.User;

            var userRolesList = _userRoleService.GetUserRolesListe();

            var currentUser = userRolesList.Where(ur => ur.WindowsUser == user.Identity?.Name)
                                    .ToList();
            if (currentUser != null)
            {
                foreach (var roleId in currentUser)
                {
                    var claimsIdentity = (ClaimsIdentity)user.Identity!;
                    claimsIdentity.AddClaim(new Claim(ClaimTypes.GroupSid, roleId.RoleId.ToString()));
                }
            }
        }

I tried following the steps from the Microsoft doc.

UserRoleHub.cs:

using Microsoft.AspNetCore.SignalR;

namespace MultipleProjectsSyncfusion.Hubs
{
    public class UserRoleHub : Hub
    {
        public async Task UpdateUserRoles(string userId)
        {
            await Clients.All.SendAsync("UpdateRoles", userId);
        }
    }
}

Change in my UserRoleManager.cs:

public async Task UpdateUserRole()
{
 //.. irrelevant Code 
            var username = currentUser.FirstOrDefault(ur => ur.WindowsUser == user.Identity?.Name);

            var hubContext = _hubContext.Clients.All;
            await hubContext.SendAsync("UpdateUserRoles", username?.WindowsUser);
}

Admin.razor

protected override async Task OnInitializedAsync()
    {
        // irrelevant Code 

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

        hubConnection.On<string>("ReceiveRoleChangeNotification", async (user) =>
        {

            SelectedUser = user;
            StateHasChanged(); // Aktualisiere die Benutzeroberfläche

        });


        await hubConnection.StartAsync();
    }

Error: This is the Error which I get after running my Blazor Server Projekt: HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).

0

There are 0 answers