401 Unauthorized Error When Connecting WinForms to Azure SignalR Service

I’m working on a WinForms application that needs to connect to an Azure SignalR Service hosted on a web app. I’m encountering a 401 Unauthorized error when trying to establish the SignalR connection.

Here is the code I’m using to initialize the SignalR connection in my WinForms app:

private async void InitializeSignalRConnection()
{
    await Task.Delay(5000);
    try
    {
        string token = await GetSignalRAccessToken();

        connection = new HubConnectionBuilder()
            .WithUrl("https://your-signalr-endpoint/client/?hub=notifications", options =>
            {
                options.AccessTokenProvider = () => Task.FromResult(token);
            })
            .WithAutomaticReconnect()
            .Build();

        await connection.StartAsync();
        
        connection.On<TransactionData>("SendMessageToClients", async (transactionData) =>
        {
            MessageBox.Show($"Transaction Received in WinForms: {transactionData.TransactionId}");
            await connection.InvokeAsync("AcknowledgeTransaction", transactionData.TransactionId, "Received and Processed by WinForms");
        });

        Console.WriteLine("SignalR connection started.");
    }
    catch (Exception ex)
    {
        MessageBox.Show($"Error initializing SignalR connection: {ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
}

Here is the relevant configuration from my web app:

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddRazorPages();
builder.Services.AddCors(options => options.AddPolicy("testing", policy =>
{
    policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
}));

string azureSignalRConnectionString = builder.Configuration.GetValue<string>("AzureSignalRConnectionString");
builder.Services.AddSignalR().AddAzureSignalR(azureSignalRConnectionString);
builder.Services.AddControllers();

var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("testing");
app.UseAuthorization();
app.MapHub<NotificationHub>("/notifications");
app.MapControllers();
app.MapRazorPages();
app.Run();

What I’ve Tried:

Verified the SignalR connection URL.
Checked CORS policy settings.
Confirmed that the token is correctly generated and passed.

Expected Result:

Successful connection to the SignalR hub.
Actual Result:

401 Unauthorized error.
Any help on what might be causing this issue would be greatly appreciated.

2

You are passing an access token, but the server-side configuration doesn’t show any JWT or token validation setup in the above.

Add JWT Authentication to the Server

Program.cs:

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using System.Text;

var builder = WebApplication.CreateBuilder(args);

// Add Razor Pages and other services
builder.Services.AddRazorPages();
builder.Services.AddCors(options => options.AddPolicy("testing", policy =>
{
    policy.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin();
}));

// Add JWT Authentication
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuer = true,
            ValidateAudience = true,
            ValidateLifetime = true,
            ValidateIssuerSigningKey = true,
            ValidIssuer = "your-issuer-url",     // Replace with your issuer URL
            ValidAudience = "your-audience",     // Replace with your audience
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes("your-signing-key")) // Your signing key
        };

        // Allow SignalR access token to be passed as a query string
        options.Events = new JwtBearerEvents
        {
            OnMessageReceived = context =>
            {
                var accessToken = context.Request.Query["access_token"];

                // If the request is for the SignalR hub
                var path = context.HttpContext.Request.Path;
                if (!string.IsNullOrEmpty(accessToken) && path.StartsWithSegments("/notifications"))
                {
                    context.Token = accessToken;
                }
                return Task.CompletedTask;
            }
        };
    });

// Add SignalR and use Azure SignalR Service
string azureSignalRConnectionString = builder.Configuration.GetValue<string>("AzureSignalRConnectionString");
builder.Services.AddSignalR().AddAzureSignalR(azureSignalRConnectionString);

builder.Services.AddControllers();

// Build the app
var app = builder.Build();

app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseCors("testing");
app.UseAuthentication();  // Make sure to include this line for authentication
app.UseAuthorization();

app.MapHub<NotificationHub>("/notifications");
app.MapControllers();
app.MapRazorPages();
app.Run();

NOTE: Check that the token audience (aud) claim matches the SignalR endpoint URL.

On Client-Side add logging like below:

connection = new HubConnectionBuilder()
    .WithUrl("https://your-signalr-endpoint/client/?hub=notifications", options =>
    {
        options.AccessTokenProvider = () => Task.FromResult(token);
    })
    .WithAutomaticReconnect()
    .ConfigureLogging(logging =>
    {
        logging.SetMinimumLevel(LogLevel.Debug);  // Set to debug for detailed logs
        logging.AddConsole();
    })
    .Build();

Token Generated:

Successful Connection:

[DEBUG] - Generated Token: eyJodHRwOiJ... (a long JWT token)

[DEBUG] - Token Claims:
  iss: https://issuer-url/
  aud: https://signalr-endpoint/client/?hub=notifications
  exp: 1694997200
  sub: [email protected]

[DEBUG] - Attempting to establish SignalR connection to: https://your-signalr-endpoint/client/?hub=notifications

[DEBUG] - Connection state: Connecting

[INFO] - SignalR connection started successfully.

[DEBUG] - Transaction Received in WinForms: TX12345

[DEBUG] - Acknowledging transaction TX12345: "Received and Processed by WinForms"

Recognized by Microsoft Azure Collective

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật