SignalAir from .NET Maui app

Nando Ferreira 0 Reputation points
2024-09-26T20:53:04.7133333+00:00

I'm having error 401 Unauthorized with this code:

using Microsoft.AspNetCore.SignalR.Client;

using System.Collections.ObjectModel;

namespace ChatSignalAir;

public partial class MainPage : ContentPage

{

private readonly HubConnection _hubConnection;

private readonly ObservableCollection<string> _messages = new ObservableCollection<string>();

public MainPage()

{

    InitializeComponent();

    MessagesListView.ItemsSource = _messages;

    _hubConnection = new HubConnectionBuilder()

        .WithUrl("https://saservice.service.signalr.net/client/?hub=chat", options =>

        {

            options.AccessTokenProvider = () => Task.FromResult("mykey");

              

            // Ignore certificate verification

            options.HttpMessageHandlerFactory = messageHandler =>

            {

                var handler = new HttpClientHandler

                {

                    ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => true // Ignores verification errors

                };

                return handler;

            };

        })

        .Build();

    _hubConnection.On<string, string>("ReceiveMessage", (user, message) =>

        MainThread.BeginInvokeOnMainThread(() => _messages.Add($"{user}: {message}"))

    );

    ConnectToHubAsync();

}

private async void ConnectToHubAsync()

{

    try

    {

        await _hubConnection.StartAsync();

    }

    catch (HttpRequestException httpEx)

    {

        // Here you can capture error details

        await DisplayAlert("Error", $"Failed to connect: {httpEx.StatusCode} - {httpEx.Message}", "OK");

    }

    catch (Exception ex)

    {

        await DisplayAlert("Error", $"Unexpected error: {ex.Message}", "OK");

    }

}

private async void OnSendClicked(object sender, EventArgs e)

{

    if (_hubConnection.State != HubConnectionState.Connected)

    {

        await DisplayAlert("Error", "Connection to SignalR is not active.", "OK");

        return;

    }

    var message = MessageEntry.Text?.Trim();

    if (string.IsNullOrEmpty(message))

    {

        await DisplayAlert("Warning", "Message cannot be empty.", "OK");

        return;

    }

    try

    {

        await _hubConnection.InvokeAsync("SendMessage", "User", message); // Adjust as necessary

        MessageEntry.Text = string.Empty;

    }

    catch (Exception ex)

    {

        await DisplayAlert("Error", $"Error sending message: {ex.Message}", "OK");

    }

}

}

Azure SignalR Service
Azure SignalR Service
An Azure service that is used for adding real-time communications to web applications.
151 questions
.NET MAUI
.NET MAUI
A Microsoft open-source framework for building native device applications spanning mobile, tablet, and desktop.
3,767 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 68,636 Reputation points
    2024-09-26T21:19:52.18+00:00

    I doubt that "mkey" is a valid jwt access token. your code need to get a valid access token (which are normally good for about 20 minutes). for Maui you would typically use the msal library to get the token.

    https://learn.microsoft.com/en-us/entra/external-id/customers/tutorial-mobile-app-maui-sign-in-sign-out

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.