7

My friend and I are running into CORS trouble with our API and angular client. We are trying to establish a link, we are using signalR and the client(Angular 7) registers himself to receive messages from server(ASP .NET core 2.2).

In the browser console, I'm receiving this message :

Access to XMLHttpRequest at 'https://ourEndpoint/CoordinatorHub/negotiate' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Server side

Our startup.cs looks like this, we have followed microsoft docs

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddDbContext<OneRoomContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("OneRoomContext")));
    services.AddSignalR();
    // Register the Swagger services
    services.AddSwaggerDocument();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseDeveloperExceptionPage();
    app.UseCors(builder =>
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader()
               .AllowCredentials());
    //if (env.IsDevelopment())
    //{
    //    app.UseDeveloperExceptionPage();
    //    app.UseCors(builder =>
    //        builder.AllowAnyOrigin()
    //               .AllowAnyMethod()
    //               .AllowAnyHeader());
    //}
    //else
    //{
    //    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
    //    app.UseHsts();
    //}
    app.UseSignalR(route =>
    {
        route.MapHub<CoordinatorHub>("/CoordinatorHub");
    });
    app.UseHttpsRedirection();
    app.UseMvc();
    // Register the Swagger generator and the Swagger UI middlewares
    app.UseSwagger();
    app.UseSwaggerUi3();
}

And this is our controller :

using Microsoft.AspNetCore.SignalR;
using oneroom_api.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace oneroom_api.SignalR
{
    public class CoordinatorHub : Hub
    {
        public Task SendNewUser(User user)
        {
            return Clients.All.SendAsync("GetNewUser", user);
        }
    }
}

Azure portal : CORS allowed * origins

Client side

This is how our app.component.ts looks like (ngOnInit)

We are using @aspnet/signalr package

this.hubConnection = new signalR.HubConnectionBuilder()
    .withUrl(localStorage.getItem('endpoint') + '/CoordinatorHub')
    .build();

this.hubConnection.on('send', data => {
  console.log(data);
});

this.hubConnection.start().then(() => this.hubConnection.invoke('send', 'Hello'));

How to disable credentials mode or where do I need to give the withCredentials status ?

Thank you for your time and answers
1
  • @johnny5 no there is nothing wrong with configuring CORS in the Configure method. It is definetely not deprecated. Configuring CORS policies in the ConfigureService method is just a different and more flexible way of doing it. See the official documentation for ASP.NET Core 2.2 learn.microsoft.com/en-us/aspnet/core/security/… Commented Feb 21, 2019 at 18:25

2 Answers 2

13

As the error message already states, you need to explictly specify the allowed CORS origins.

The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.

You could of course try to make SignalR stop making a request that requires your API to send a Access-Control-Allow-Credentials header, depending on how you intend to handle authentication (cookies or bearer token?). How ever this is much more complicated than simply extending the "allowed origin" list. Besides that, you really should avoid using wildcards for the origin, especially on production systems.

For local development it is sufficient to add the address of your development server to the list of allowed origins. The list must be extended for each address you want the application to be reachable under.

 app.UseCors(builder =>
    builder.WithOrigins("http://localhost:4200")
           .AllowAnyMethod()
           .AllowAnyHeader()
           .AllowCredentials());

In addition to the code changes, you must remove the wildcard CORS entry from your Azure App Service configuration. Otherwise the changes would have no effect, because the CORS header would get overwritten by Azure.

Sign up to request clarification or add additional context in comments.

4 Comments

As you can see, there's already this line on our startup. Your patch doens't work for us.
No it's not. The code you posted says builder.AllowAnyOrigin(), which causes the API to send a Access-Control-Allow-Origin: * header.
What doesn't work? Do you still get the same error message? How do the headers of the response look like?
We use AnyOrigin() in our code and it seems to work OK. In fact our configuration looks pretty much the same as the above
1

Basically the problem was the CORS on azure overwrote the code in our startup.cs, we ended up removing the configuration CORS on our azure portal and everything works. We have used signal R npm package with angular since the old signalR-client is deprecated.

2 Comments

I provided a full answer (including the hint about disabling CORS on Azure) in my answer days ago. Your answer is only partially complete, as it does not go into solving the wildcard error. Nevertheless I'm glad that you were able to find the problem yourself.
Yeah sorry, I saw it just now you updated the answer the 21, and I missed it, still thank you for your time !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.