121

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?

11
  • 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.
    – user47589
    Commented Dec 7, 2018 at 19:41
  • @Amy And what the solution?
    – Igor Cova
    Commented Dec 7, 2018 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."
    – user47589
    Commented Dec 7, 2018 at 19:42
  • 2
    Again, this needs to be set on the server, not in your client.
    – user47589
    Commented Dec 7, 2018 at 20:23
  • 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
    Commented Dec 8, 2018 at 12:18

7 Answers 7

121

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

3
  • 14
    Yes, this was applicable for me when upgrading from Asp.Net Core 2.1 to Asp.Net Core 3.1 Commented Feb 14, 2020 at 10:34
  • 1
    Thanks, one bug less while upgrading to Net Core 3.1 from Net Core 2.2 :)
    – Fellow7000
    Commented Jun 15, 2020 at 23:26
  • Thanks. That was the issue for me also! Commented Jun 12, 2021 at 15:09
67

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));
            });
3
  • 13
    This should be accepted answer, allows AnyOrigin and Credentials at the same time.
    – tomec
    Commented Mar 2, 2020 at 14:00
  • 3
    This is very dangerous if the server is publicly accessible, see ejj.io/misconfigured-cors Commented Jul 14, 2021 at 15:23
  • 1
    Some APIs are designed to be consumed from customers sites like integrations. This is the correct answer as long as you know what you are doing and apply it only to the correct controllers etc. Commented Jan 24 at 10:55
63

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...

2
  • 8
    Credentials cannot be used with any origin. See the comments on the question.
    – user47589
    Commented Dec 7, 2018 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
    Commented Dec 8, 2018 at 5:28
51

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.

3
  • 1
    I had to add "app.UseCors" under Configure in Startup.cs to get this to work Commented Apr 13, 2020 at 18:11
  • Thanks Kurniawan Prasetyo. Your solution has worked for me! :)
    – Mily
    Commented Aug 3, 2020 at 9:04
  • OMG, I love you I have been searching for something like this last 2 days! Commented Oct 22, 2020 at 15:20
22

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

9

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());
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  !!!

    

Not the answer you're looking for? Browse other questions tagged or ask your own question.