dotnet / AspNetCore.Docs

Documentation for ASP.NET Core
https://docs.microsoft.com/aspnet/core
Creative Commons Attribution 4.0 International
12.64k stars 25.28k forks source link

Add content about enabling CORS for SignalR without applying the policy globally. #12918

Open ryan-h opened 5 years ago

ryan-h commented 5 years ago

I encountered a situation where the CORS policy used for SignalR could not be enabled as the middleware default for the entire application. Instead I needed to use a specific policy only for the requests to the SignalR hubs.

Maybe it would be helpful to add a subsection about "Cross-origin resource sharing" that describes how to branch the request pipeline in order to apply a CORS policy specifically for SignalR, which would then allow an application to use attributes to enable CORS elsewhere instead of using middleware.

public void Configure(IApplicationBuilder app)
{
    ...

    app.Map("/hubs", config =>
    {
         // Must be called before mapping SignalR hubs
         config.UseCors(builder =>
         {
             builder.WithOrigins("https://myorigin:5000")
                 .WithMethods("Get", "Post")
                 .AllowAnyHeader()
                 .AllowCredentials();
         });

         config.UseSignalR(routes =>
         {
             routes.MapHub<ChatHub>("/chat");
         });
    });
}

Document Details

Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

BrennanConroy commented 4 years ago

There are 2 ways to do this assuming a named policy has been added

services.AddCors(o =>
{
    o.AddPolicy("SignalRPolicy", o2 =>
    {
        o2.WithOrigins("https://example.com")
            .AllowAnyHeader()
            .WithMethods("GET", "POST")
            .AllowCredentials();
    });
});

1.

endpoints.MapHub<Chat>("/default").RequireCors("SignalRPolicy");

2.

[EnableCors("SignalRPolicy")]
public class Chat : Hub
{
}

And can cross-ref to https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#enable-cors-with-endpoint-routing