'Access-Control-Allow-Origin' in ASP.NET Core 6
Asked Answered
A

7

14

Tested in Postman and works fine. In Browser I get this Error:

Access to XMLHttpRequest at 'http://localhost:5081/api/Accounting/GetSales' from origin 'https://localhost:44426' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Asp Net Core Project with Angular and .Net6

[DisableCors]
[HttpGet("GetSales")]
        public IEnumerable<SaleDto> GetSales()
        {
            var result = _context.Sales.Select(x => new SaleDto
            {
                AccountName = x.Account.Name,
                CategoryName = x.Category.CategoryName,
                SaleDate = x.SaleDate,
                SaleId = x.SaleId,
                SaleValue = x.SaleValue,
            });
            return result;
        }
Anthropophagite answered 4/1, 2022 at 21:33 Comment(4)
you have to expose the cors on the server. DisableCors defeats thatChowder
Postman does not care about CORS. The browser does. You explicitely disabled CORS for that call, so why do you wonder it doesn't work?Nit
Tested it without DisableCors and still not working.Anthropophagite
So, have you configured CORS? learn.microsoft.com/en-us/aspnet/core/security/…Nit
C
8

Do you have the proper entries when you register the middleware? Enable Cross-Origin Requests (CORS) in ASP.NET Core.

You will need to add localhost and the port numbers. I believe the port numbers are currently causing the issue right now. If both sites were on the same port number you might not get this issue. Also, see the answers for CORS error on same domain. CORS error on same domain?

Also, you want to enable CORS not disable it. CORS relaxes the security measures so your code can reach across ports.

Conveyancer answered 4/1, 2022 at 21:45 Comment(0)
H
6

What works for me was putting

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

before

app.UseRouting();

app.UseEndpoints(endpoints =>
{
    endpoints.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
});

in your Program.cs or startup.cs

then you can alter your configrations

Hadley answered 16/1, 2023 at 18:2 Comment(2)
According to the Microsoft docs app.UseCors() should be placed after app.UseRouting() See: learn.microsoft.com/en-us/aspnet/core/security/….Magalimagallanes
@GeorgeFeakes I noticed that too but I couldn't get it to work that way... The solution of Wowo Ot works, but I don't know why. I don't know why MS's intended way doesn't work.Metopic
S
4

Another thing to check is make sure your origin is spelled out exactly.

I had "http://localhost:4200/" as the origin somehow, instead of "http://localhost:4200".

Took a lot of hours to figure that out.

Sestos answered 25/8, 2023 at 19:24 Comment(0)
G
1

In Appsetting.json file { "AllowOrigins": "https://localhost:4200" }

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
       
        var allowOrigins = Configuration.GetValue<string>("AllowOrigins");
        services.AddCors(options =>
        {
            options.AddPolicy("CorsPolicy", builder =>
            {
                builder.WithOrigins(allowOrigins)
                    .AllowAnyHeader()
                    .AllowAnyMethod()
                  .AllowCredentials();
            });
            options.AddPolicy("AllowHeaders", builder =>
            {
                builder.WithOrigins(allowOrigins)
                        .WithHeaders(HeaderNames.ContentType, HeaderNames.Server, HeaderNames.AccessControlAllowHeaders, HeaderNames.AccessControlExposeHeaders, "x-custom-header", "x-path", "x-record-in-use", HeaderNames.ContentDisposition);
            });
        });
        services.AddSwaggerGen(c =>
        {
            c.SwaggerDoc("v1", new OpenApiInfo { Title = "DatingApp", Version = "v1" });
        });
        //authentication
        

                                                                                                                                                                                                                                            
    }

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        app.UseMiddleware<ExceptionMiddleware>();
        app.UseSwagger();
        app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "DatingApp v1"));

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

        app.UseHttpsRedirection();

        app.UseRouting();

        app.UseCors("CorsPolicy");
        //authentication
        app.UseAuthentication();
        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

}

Girardo answered 7/9, 2022 at 17:36 Comment(1)
strangely, .AllowCredentials didn't pop up in the context sensitive help... but when I trusted your answer and added it, it worked like a champ... so thanks !!!!!Noranorah
L
0

I had a similar issue, I tried changing the header from the part of the front-end from where I was doing the calls and then directly to the controller but what worked for me was changing the Start.cs file of the API project and add the following. I recommend trying it first in localhost and then deploying the changes where you actually have the API.

public class Startup
{
    private readonly string _MyCors = "MyCors";
    .
    .
    .
    public void ConfigureServices(...)
    {
        .
        .
        .
        //Under your services.AddControllers();
        services.AddCors(options =>
        {
            options.AddPolicy(name: _MyCors, builder =>
            {
                //for when you're running on localhost
                builder.SetIsOriginAllowed(origin => new Uri(origin).Host == "localhost") 
                .AllowAnyHeader().AllowAnyMethod();


                //builder.WithOrigins("url from where you're trying to do the requests")
            });
        });
    }
    public void Configure(.....)
    {
        //before the app.UseAuthorization & app.UseEndpoints
        app.UseCors(_MyCors);
    }
}
Lothario answered 27/7, 2022 at 18:37 Comment(0)
P
0

Source 1 and Source 2

First install following package

Install-Package Microsoft.AspNetCore.Cors

Allow all origins, headers and methods

Add middleware in Program.cs file, this is easy way but now anyone can access the API.

app.UseHttpsRedirection();
app.UseCors(options =>
{
    options.AllowAnyHeader();
    options.AllowAnyOrigin();
    options.AllowAnyMethod();
});

app.UseAuthentication();
app.UseAuthorization();

Allow Specific Origins

This is the right way to do it

builder.Services.AddCors(options =>
{
     options.AddDefaultPolicy({
          policy.WithOrigins("https://weblink.com"); //do not put slash at the end
     });
});

app.UseCors();

The above will only work for GET, HEAD and POST type of requests. For other types you need to allow the methods.

builder.Services.AddCors(options =>
{
     options.AddDefaultPolicy({
          policy
              .WithOrigins("https://weblink.com")
              .WithMethods("PUT", "DELETE");
     });
});

app.UseCors();
Passmore answered 7/5 at 10:40 Comment(0)
I
0

I Had similar issue raised by app sec team.

Issue was :"It was observed that in the application when the origin is manipulated with a malicious url , it gets reflected in the response headers i.e Access-control-Allow-Origin reflects the malicious url which means the domain can access resources from the vulnerable domain."

To resolved this made below mentioned changes on cors policy:

builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowSpecificOrigin",
           builder => builder
           .AllowAnyMethod()
           .AllowAnyHeader()
           //.AllowCredentials()
           //.SetIsOriginAllowed(hostName => true)
           .WithOrigins("https://localhost:443/"));
});




app.UseCors("AllowSpecificOrigin");

this will remove

Access-control-Allow-Origin

key from response header.

hope this will resolved your issue.

Iny answered 3/7 at 12:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.