Skip to content
42 changes: 41 additions & 1 deletion aspnetcore/signalr/security.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,15 @@
---
title: Security considerations in ASP.NET Core SignalR
ai-usage: ai-assisted
author: wadepickett
description: Learn about security in ASP.NET Core SignalR.
monikerRange: '>= aspnetcore-2.1'
ms.author: wpickett
ms.custom: mvc
ms.date: 02/20/2024
ms.date: 03/31/2026
Comment thread
wadepickett marked this conversation as resolved.
uid: signalr/security
---

# Security considerations in ASP.NET Core SignalR

By [Andrew Stanton-Nurse](https://twitter.com/anurse)
Expand Down Expand Up @@ -39,6 +41,44 @@ For example, the following highlighted CORS policy allows a SignalR browser clie

In the previous example, the CORS policy is customized to allow specific origins, methods, and credentials. For more information on customizing CORS policies and middleware in ASP.NET Core, see [CORS middleware: CORS with named policy and middleware](xref:security/cors#cors-with-named-policy-and-middleware).

### Apply a CORS policy to SignalR hub endpoints

Instead of applying a CORS policy globally with the `UseCors` middleware, you can apply CORS specifically to SignalR hub endpoints. This approach allows different CORS policies for different parts of the app.

There are two ways to apply a CORS policy to SignalR hubs: chaining `RequireCors` on the endpoint mapping, or adding the `[EnableCors]` attribute to the Hub class. Both approaches require a named CORS policy to be registered in the service configuration. The following example defines a policy named `"SignalRPolicy"`:

```csharp
builder.Services.AddCors(options =>
{
Comment thread
wadepickett marked this conversation as resolved.
options.AddPolicy("SignalRPolicy", policy =>
{
policy.WithOrigins("https://example.com")
.AllowAnyHeader()
.WithMethods("GET", "POST")
.AllowCredentials();
});
});
```

**Apply the CORS policy on the hub endpoint mapping** by chaining <xref:Microsoft.AspNetCore.Builder.CorsEndpointConventionBuilderExtensions.RequireCors%2A> on the `MapHub` call:

```csharp
app.MapHub<ChatHub>("/chatHub")
Comment thread
wadepickett marked this conversation as resolved.
.RequireCors("SignalRPolicy");
```

**Apply the CORS policy on the Hub class** by adding the [`[EnableCors]`](xref:Microsoft.AspNetCore.Cors.EnableCorsAttribute) attribute:

```csharp
[EnableCors("SignalRPolicy")]
public class ChatHub : Hub
{
// ...
}
```

For more information on enabling CORS with endpoint routing, see [Enable CORS with endpoint routing](xref:security/cors#enable-cors-with-endpoint-routing).

## WebSocket Origin Restriction

The protections provided by CORS don't apply to WebSockets. For origin restriction on WebSockets, read [WebSockets origin restriction](xref:fundamentals/websockets#websocket-origin-restriction).
Expand Down
Loading