110

I've already enabled CORS on the project in C# .net Core

In startup.cs I've added lines

...
services.AddCors();
...
app.UseCors(builder => builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());

But when I try to use API in another Blazor project I see in logs in my API project on Host this error

The CORS protocol does not allow specifying a wildcard (any) origin and credentials at the same time. Configure the policy by listing individual origins if credentials needs to be supported

My code in Blazor

using (HttpClient http = new HttpClient()) {
  http.DefaultRequestHeaders.Add("Authorization", "Token");
   var response = await http.GetStringAsync("https://example.com?prm=2");
   Console.WriteLine(response);
   dynamicContent = response;
}

Before I enable Cors I see another error in the browser console

What can I change for solving it?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
Igor Cova
  • 3,126
  • 4
  • 31
  • 57
  • 1
    The error is pretty clear. You can't specify `*` for the origin when using credentials. Set the origin to your server's actual domain name. Also, these headers must be set *by the server*, not in your client headers. –  Dec 07 '18 at 19:41
  • @Amy And what the solution? – Igor Cova Dec 07 '18 at 19:41
  • I already told you the solution, as does the error message. Again, "Set the origin to your server's actual domain name." –  Dec 07 '18 at 19:42
  • @Amy instead of "*" I have to put "https://example.com"? – Igor Cova Dec 07 '18 at 19:46
  • Instead of “*” please put “https://example.com” (including protocol) as suggested by Amy.. The limitation is only 1 external domain can be specified.. – estinamir Dec 07 '18 at 20:09
  • @bestinamir I did it, but the problem is not solved – Igor Cova Dec 07 '18 at 20:14
  • 2
    Again, this needs to be set **on the server**, not in your client. –  Dec 07 '18 at 20:23
  • May be try going with this approach: https://stackoverflow.com/a/44379971/10634638 – estinamir Dec 07 '18 at 20:41
  • @daniherrera Yes, You are right. It's probably a host's problem because now I've tried to call another API server and it's work well. Maybe I need to config nginx – Igor Cova Dec 08 '18 at 12:12
  • 2
    @daniherrera @amy I've solved it just drop `http.DefaultRequestHeaders.Add("Access-Control-Allow-Origin", "*");` and in row `var response = await Http.GetStringAsync("https://example.com?prm=2");` change `Http` to `http` – Igor Cova Dec 08 '18 at 12:18
  • You can follow this link, it's work for me: https://mykkon.work/how-to-setup-any-origin/ – Truc Mar 25 '20 at 10:01

7 Answers7

110

I had the same issue and I removed AllowCredentials() that fixed the issue for me.

granadaCoder
  • 26,328
  • 10
  • 113
  • 146
Nicola Di Lillo
  • 1,761
  • 1
  • 11
  • 9
61

You should have provided the rest of your code... Is this a Blazor client application or Razor Components application (formally known as Server-Side Blazor) ? I guess this is a Blazor client application, right ? Why do you instantiate an HttpClient ? You should use DI (Perhaps Constructor Injection) instead, injecting an HttpClient instance provided by Blazor itself.

The problem is probably server side, though it surfaces as a client one... Try the following:

Get https://www.nuget.org/packages/Microsoft.AspNetCore.Cors/

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options =>
    {
        options.AddPolicy("CorsPolicy",
            builder => builder.AllowAnyOrigin()
                .AllowAnyMethod()
                .AllowAnyHeader());
    });
     .....
}

And this:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)    
{
      app.UseCors("CorsPolicy");
}

Note, once again: CORS needs to be enabled on the server side, not in blazor. See https://learn.microsoft.com/en-us/aspnet/core/security/cors for details on how to enable CORS in ASP.NET Core.

Blazor:

 @page "/<template>"
 @inject HttpClient Http


@functions {

    protected override async Task OnInitAsync()
    {
        var response= await Http.GetJsonAsync<string>    
                      ("https://example.com?prm=2");

    }

}  

Hope this helps...

johnny 5
  • 19,893
  • 50
  • 121
  • 195
enet
  • 41,195
  • 5
  • 76
  • 113
  • 5
    Credentials cannot be used with any origin. See the comments on the question. –  Dec 07 '18 at 21:41
  • 1
    On the server, I have .net Core API project - and now I develop Blazor client project. In my question is shown that I add and use Cors. It's not help me – Igor Cova Dec 08 '18 at 05:28
61

It's little bit late, but I hope it could be helpful for someone.

If you want AllowCredentials() and AllowAnyOrigin() together just use SetIsOriginAllowed(Func<string,bool> predicate)

doc about IsOriginAllowed

        services
            .AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder
                    .AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    );

                options.AddPolicy("signalr",
                    builder => builder
                    .AllowAnyMethod()
                    .AllowAnyHeader()

                    .AllowCredentials()
                    .SetIsOriginAllowed(hostName => true));
            });
Konstantin Nikolskii
  • 1,075
  • 1
  • 12
  • 17
49

I also faced same issue, and I found solution here:

Setup Any Origin And Any Credentials

Change your CORS setup in startup.cs file like this

public void ConfigureServices(IServiceCollection services)
{
    // ...
    services.AddCors(options =>
    {
        options.AddDefaultPolicy(builder => 
            builder.SetIsOriginAllowed(_ => true)
            .AllowAnyMethod()
            .AllowAnyHeader()
            .AllowCredentials());
    });
}

It works for me.

19

Step 1 Install nuGet package :
Microsoft.AspNetCore.Cors

Step 2 add

services.AddCors();

in startup.cs under ConfigureServices

Step 3 add

    app.UseCors(x => x
                .AllowAnyMethod()
                .AllowAnyHeader()
                .SetIsOriginAllowed(origin => true) // allow any origin
                .AllowCredentials());

in startup.cs under Configure

B.Nishan
  • 536
  • 4
  • 13
8

You cannot use both AllowAnyOrigin() and AllowCredentials() at the sametime so change your code to:

...
services.AddCors();
...
app.UseCors(builder => builder
    .WithOrigins("https://example.com")
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials());
Mohamed Anas
  • 194
  • 2
  • 7
2

I had the same issue, the problem was solved by removing slash( / ) from the ending of URL, because I always copy and paste urls from chrome browser and it has the / at the end :

  .WithOrigins("https://localhost:60576/")  // not working 

but

  .WithOrigins("https://localhost:60576")  // working  !!!

    
nAviD
  • 2,784
  • 1
  • 33
  • 54