blazor-starter-kit icon indicating copy to clipboard operation
blazor-starter-kit copied to clipboard

Implement another SignalR Hub with Authentication and StreamAsync <byte[]> to process big data

Open Waynecool5 opened this issue 4 years ago • 1 comments

I want to test a solution in BlazorHero.

It's is a SignalR Hub with identityserver (Authentication, Authorization) and StreamAsync <byte[]> to process big data on all communications via messagepack C#. I need some pointers on your authentication to authorize the hub.

Ps* I am using Dapper and MSSQL storedprocedures for data access via byte[] transfers.

Thanks

//----------------------------------------- // Client Call //------------------------- protected override async Task OnInitializedAsync() { @* _currentUser = await _authenticationManager.CurrentUser(); _canCreateBrands = (await _authorizationService.AuthorizeAsync(_currentUser, Permissions.Clients.Create)).Succeeded; _canEditBrands = (await _authorizationService.AuthorizeAsync(_currentUser, Permissions.Clients.Edit)).Succeeded; _canDeleteBrands = (await _authorizationService.AuthorizeAsync(_currentUser, Permissions.Clients.Delete)).Succeeded; _canExportBrands = (await _authorizationService.AuthorizeAsync(_currentUser, Permissions.Clients.Export)).Succeeded; _canSearchBrands = (await _authorizationService.AuthorizeAsync(_currentUser, Permissions.Clients.Search)).Succeeded; *@

    var savedUser = await _localStorage.GetItemAsync<string>(StorageConstants.Local.UserEmail);
    
    var savedToken = await _localStorage.GetItemAsync<string>(StorageConstants.Local.AuthToken);
    
    if (string.IsNullOrWhiteSpace(savedToken))
    {
        var token = await _authenticationManager.TryRefreshToken();
        savedToken = token;
    }

    hubConnectStream = hubConnectStream.TryInitializeStream(_navigationManager, savedUser, savedToken);
    if (hubConnectStream.State == HubConnectionState.Disconnected)
    {
        await hubConnectStream.StartAsync();
    }

}

//--------------------------------------- // Client Global Connection //------------------------------------ using System; using System.Threading.Tasks; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.SignalR.Client; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.WebAssembly.Authentication; using GaGenInc.Shared.Constants.Application; using Microsoft.Extensions.Configuration; using System.Security.Claims; using MessagePack; using MessagePack.Resolvers; using Microsoft.Extensions.DependencyInjection; using Microsoft.EntityFrameworkCore.ChangeTracking.Internal; using GaGenInc.Shared.Constants.Storage; using Blazored.LocalStorage; using GaGenInc.Client.Infrastructure.Managers.Identity.Authentication;

namespace GaGenInc.Client.Extensions { public static class HubStreamExtension {

    public static HubConnection TryInitializeStream(this HubConnection hubConnectStream, NavigationManager navigationManager, string User, string token)
    {
        
        if (hubConnectStream == null)
        {
            
            hubConnectStream = new HubConnectionBuilder()
            
            .WithUrl(navigationManager.ToAbsoluteUri($"{AppConstants_Stream.SignalRStream.HubUrlStream}?name={User}"), options =>
            {
                options.AccessTokenProvider = () => Task.FromResult(token);

                options.HttpMessageHandlerFactory = innerHandler =>
                    new IncludeRequestCredentialsMessageHandler { InnerHandler = innerHandler };
            })

            //.WithUrl(navigationManager.ToAbsoluteUri(AppConstants_Stream.SignalRStream.HubUrlStream))
            .AddMessagePackProtocol()
            .WithAutomaticReconnect()  //new[] { TimeSpan.Zero, TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(10) })
            .Build();
        }
   
        return hubConnectStream;
    }

}

} //--------------------------------------

Waynecool5 avatar Jul 10 '21 13:07 Waynecool5

Hi @Waynecool5 , I don't understand the question. Do you have problem authenticating the hub?

Try to use the latest source code from git repo, the template isn't aligned with latest changes.

In HubExtensions.cs you have a new method to authenticate using Localstorage access token:

public static HubConnection TryInitialize(this HubConnection hubConnection, NavigationManager navigationManager, ILocalStorageService _localStorage)
        {
            if (hubConnection == null)
            {
                hubConnection = new HubConnectionBuilder()
                                  .WithUrl(navigationManager.ToAbsoluteUri(ApplicationConstants.SignalR.HubUrl), options => {
                                      options.AccessTokenProvider = async () => (await _localStorage.GetItemAsync<string>("authToken"));
                                  })
                                  .WithAutomaticReconnect()
                                  .Build();
            }
            return hubConnection;
        }

all the call for hub connection now use the new method, like this in AddEditBrandModal.razor.cs:

protected override async Task OnInitializedAsync()
        {
            await LoadDataAsync();
            HubConnection = HubConnection.TryInitialize(_navigationManager, _localStorage);
            if (HubConnection.State == HubConnectionState.Disconnected)
            {
                await HubConnection.StartAsync();
            }
        }

nbiada avatar Aug 12 '21 05:08 nbiada