bob.mazzo
bob.mazzo

Reputation: 5627

CORS errors when deploying signalR notification Hub to IIS

My signalR Hub can run fine in VS2019 debug mode on secure port 44311, but as soon as I publish it to my local IIS on my dev box, the ../hub/negotiate fails with a CORS policy exception.

ex. in debug mode, the IIS tray

enter image description here

and signalr Hub starts fine:

enter image description here


Now onto my local Window 10 IIS settings where I deployed the signalR Hub project:

  1. I setup the https bindings
  2. I successfully setup the SSL Cert, and set the Require SSL checkbox:
  3. I Restart my IIS Website, and Browse on 44311 to test

enter image description here

enter image description here

enter image description here

But sure enough, my app cannot connect to the HUB:

Access to XMLHttpRequest at 'https://localhost:44311/hub/negotiate?negotiateVersion=1' from origin 'http://localhost:4200' has been blocked by CORS policy:

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

POST https://localhost:44311/hub/negotiate?negotiateVersion=1 net::ERR_FAILED


Yet in my code I injected CORS:

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Http.Connections;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using NotificationHub.Hubs;
namespace NotificationHub
{
    public class Startup
    {
        readonly string MyAllowedSpecificOrigins = "_myAllowedSpecificOrigins";

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowedSpecificOrigins,
                                  builder => {
                                      builder.WithOrigins("https://localhost:4200", "localhost:4200")
                                        .SetIsOriginAllowedToAllowWildcardSubdomains()
                                        .AllowAnyHeader()
                                        .AllowAnyMethod()
                                        .AllowCredentials()
                                        .SetIsOriginAllowed((host) => true);
                                  }
                                  );
            });
           
            services.AddSignalR(hubOptions => {
                hubOptions.EnableDetailedErrors = true;
                hubOptions.KeepAliveInterval = System.TimeSpan.FromMinutes(1000);
            });            
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseHttpsRedirection();
            app.UseRouting();
            app.UseCors(MyAllowedSpecificOrigins);

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            // app.UseSession();
            app.UseEndpoints(endpoints =>
            {           
                endpoints.MapHub<Notifications>("/hub", options => {
                    options.Transports = HttpTransportType.WebSockets | HttpTransportType.LongPolling;
                });
                endpoints.MapGet("/", async context =>
                {
                    await context.Response.WriteAsync("Notification HUB has started!");                    
                });
            });
        }
    }
}

I'm not sure at this point if it's a coding issue (i.e. not setting CORS properly), or a deployment issue.

Help is appreciated.

thanks.

UPDATE

As per the suggested answer below, my CORS issue is resolved when deployed to IIS:

  1. Install cors for IIS: https://www.iis.net/downloads/microsoft/iis-cors-module
  2. Add below <customHeaders> to web.config

However, I still CANNOT connect to the hub successfully in IIS deployment mode (http://localhost:55271/hub/negotiate?negotiateVersion=1 throws 404 not found); however debug works fine.

<httpProtocol>
        <customHeaders>
          <add name="Access-Control-Allow-Origin" value="http://localhost:4200" />
          <add name="Access-Control-Allow-Credentials" value="true" />
          <add name="Access-Control-Request-Headers" value="User-Agent,Content-Type,Authorization,X-RequestDigest,X-ClientService-ClientTag,XMLHttpRequest,x-requested-with" />
          <add name="Access-Control-Allow-Headers" value="User-Agent,Content-Type,Authorization,X-RequestDigest,X-ClientService-ClientTag,XMLHttpRequest,x-requested-with" />
          <add name="Access-Control-Request-Method" value="GET,POST,HEAD,OPTIONS" />
        </customHeaders>
      </httpProtocol>

Upvotes: 0

Views: 988

Answers (1)

Jalpa Panchal
Jalpa Panchal

Reputation: 12749

make sure you enabled iis .net feature. enable directory browsing in iis for the site:

1)Start IIS Manager.

2)In IIS Manager, expand the server name, expand Web sites, and then select the website.

3)In the Features view, double-click Directory Browsing.

4)In the Actions pane, click Enable.

add below code in web.config file:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://my-external-app-domain.com" />
    <add name="Access-Control-Allow-Credentials" value="true" />
    <add name="Access-Control-Request-Headers" value="User-Agent,Content-Type,Authorization,X-RequestDigest,X-ClientService-ClientTag" />
    <add name="Access-Control-Request-Method" value="GET,POST,HEAD,OPTIONS" />
  </customHeaders>
</httpProtocol>
</system.webServer>

install cors module in iis by using web platform installer or from below link:

https://www.iis.net/downloads/microsoft/iis-cors-module

Update:

Add below to web.config:

HttpRequest,x-requested-with were both needed in "Access-Control-Request-Headers" . In addition, I inserted header name="Access-Control-Allow-Headers" with same values as Request-Headers.

Upvotes: 1

Related Questions