Home > Blockchain >  Error with CORS when calling local c# api from an Angular project
Error with CORS when calling local c# api from an Angular project

Time:05-21

I'm trying to call a local api developed in C# from another project developed in Angular.

Everytime I try to call a method from the api I get this error:

Access to XMLHttpRequest at 'https://localhost:7239/users/getPrivacySettings' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried to change the cores policy in the api to the following and none of them worked:

  • policy.AllowAnyOrigin();
  • policy.AllowAnyOrigin().AllowAnyMethod();
  • policy.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader;
  • policy.WithOrigins("https://localhost:4200").SetIsOriginAllowedToAllowWildcardSubdomains().AllowAnyMethod().AllowAnyHeader();

I also tried to create a web.config file(it wasn't created with the project) and add the configurations directy there but it also made nothing.

<system.webServer>
      <httpProtocol>
          <customHeaders>
              <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
              <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
          </customHeaders>
      </httpProtocol>
      <rewrite>
          <outboundRules>
              <clear />
              <rule name="AddCrossDomainHeader">
                  <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                  <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                      <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((. \.)?domain1\.com|(. \.)?domain2\.com|(. \.)?domain3\.com))" />
                  </conditions>
                  <action type="Rewrite" value="{C:0}" />
              </rule>
          </outboundRules>
      </rewrite>
      
    <aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
  </system.webServer>

Here is my program.cs file

using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.IdentityModel.Tokens;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.Filters;
using System.Text;

var builder = WebApplication.CreateBuilder(args);
string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";
// Add services to the container.

builder.Services.AddControllers();


// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();


builder.Services.AddHttpContextAccessor();
builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins, policy =>
    {
        policy.WithOrigins("https://localhost:4200").SetIsOriginAllowedToAllowWildcardSubdomains().AllowAnyMethod().AllowAnyHeader();
    });
});

builder.Services.AddSwaggerGen(options =>
{
    options.AddSecurityDefinition("oauth2", new OpenApiSecurityScheme
    {
        Description = "Standard Authorization header using the Bearer scheme (\"bearer {token}\")",
        In = ParameterLocation.Header,
        Name = "Authorization",
        Type = SecuritySchemeType.ApiKey
    });

    options.OperationFilter<SecurityRequirementsOperationFilter>();
});
builder.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
    .AddJwtBearer(options =>
    {
        options.TokenValidationParameters = new TokenValidationParameters
        {
            ValidateIssuerSigningKey = true,
            IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8
                .GetBytes("my top secret key")),
            ValidateIssuer = false,
            ValidateAudience = false
        };
    });

DependencyInjection dependencyInjection = new(builder.Configuration);
dependencyInjection.InjectDependencies(builder.Services);

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}


app.UseHttpsRedirection();
app.UseCors();

app.UseAuthentication();

app.UseAuthorization();

app.MapControllers();

app.Run();

Any help is welcomed.

CodePudding user response:

The problem is that you are not specifying the CORS policy that should be used on the app.UseCors method, as shown in the documentation here; for your case this would be:

app.UseCors(MyAllowSpecificOrigins);

Also, I will recommend you to change your CORS policy to the following:

builder.Services.AddCors(options =>
{
    options.AddPolicy(name: MyAllowSpecificOrigins, policy => policy.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod());
});

This is because you don't need (at least for now) to allow wildcard subdomains for the policy.

As a bonus, you can also set the default CORS policy instead, as shown in the documentation here.

builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy => policy.WithOrigins("http://localhost:4200").AllowAnyHeader().AllowAnyMethod());
});

// ...

app.UseCors();
  • Related