Course contentsShow
← C#
Lesson 1468 of 1,90813. Real-time Communication with SignalRFree lesson

Handling CORS Policies for Cross-Origin Clients

Configure strict origin white-listing to prevent unauthorized third-party cross-origin connections.

In this lesson, you will learn how to secure your SignalR hubs by implementing strict CORS policies that restrict real-time connections to only your trusted web domains.

Understanding the CORS Requirement

By default, browsers enforce the Same-Origin Policy, which prevents scripts on one site from accessing resources on another. Because SignalR relies on HTTP-based negotiation and WebSockets to establish a connection, it is subject to these same browser protections. If you deploy a client application on https://trusted-client.com, but your SignalR hub sits on https://api.my-app.com, the browser will block the connection unless you explicitly whitelist the origin.

Implementing Strict Whitelisting

To prevent unauthorized third-party sites from hosting a malicious client that attempts to connect to your hub, you should never use AllowAnyOrigin() in production. Instead, define an explicit policy that permits only your known, secure client domains.

You configure this in your Program.cs during the service registration phase:

builder.Services.AddCors(options =>
{
    options.AddPolicy("SignalRPolicy", policy =>
    {
        policy.WithOrigins("https://trusted-client.com") // Strict whitelist
              .AllowAnyHeader()
              .AllowAnyMethod()
              .AllowCredentials(); // Required for SignalR cookies/auth tokens
    });
});

// ... later in the pipeline
app.UseCors("SignalRPolicy");
app.MapHub<ChatHub>("/chatHub");

Why Precision Matters

Using .WithOrigins("https://trusted-client.com") is a critical security boundary. By providing the exact protocol, domain, and port, you ensure that even if an attacker hosts a script on https://malicious-site.com that tries to initiate a WebSocket handshake with your Hub, the browser will block the request because the origin does not match your whitelist.

Note the use of .AllowCredentials(). SignalR requires this because it often transmits authentication headers or cookies during the initial handshake. Without this, the browser will reject the handshake even if the origin is correct. By keeping the list restricted, you effectively minimize the surface area for Cross-Site WebSocket Hijacking (CSWH) attacks.

Key Takeaway: Always whitelist specific, trusted origins in your CORS policy to prevent unauthorized cross-origin clients from establishing persistent connections with your SignalR hubs.