Thomas Segato
Thomas Segato

Reputation: 5257

CORS in asp.net core 2.1 and angular

There is quite a lot of discussions on this subject, however none is working for me. I have a asp.net core api 2.1 with an angular 7 app.

Error:

"fleet:1 Access to XMLHttpRequest at 'https://localhost:44354/api/test' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource."

Startup:

public void ConfigureServices(IServiceCollection services)
{
    services.AddAuthentication(AzureADDefaults.BearerAuthenticationScheme.AddAzureADBearer(options => Configuration.Bind("AzureAd", options));

    services.AddCors((options =>
    {
        options.AddPolicy("AzurePolicy", builder => builder
                    .WithOrigins("http://localhost:4200", "https://localhost:4200", "Access-Control-Allow-Origin", "Access-Control-Allow-Credentials")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials()
         );
    }));

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("AzurePolicy");
    app.UseAuthentication();

    app.UseMvc();
}

Config:

{
  "AzureAd": {
    "Instance": "https://login.microsoftonline.com/",
    "Domain": "xx.com",
    "TenantId": "xx",
    "ClientId": "xx"
  },
  "Logging": {
    "LogLevel": {
      "Default": "Warning"
    }
  },
  "AllowedHosts": "*"
}

I even added following to controller:

 [EnableCors("AllowSpecificOrigin")]

Is there more things you can do here?

Upvotes: 1

Views: 172

Answers (1)

Adrita Sharma
Adrita Sharma

Reputation: 22203

Add AzureActiveDirectory settings in appsettings.json

Like this:

"AzureAd": {
  "Instance": "https://login.microsoftonline.com",
  "Domain": "AD_DOMAIN",
  "TenantId": "TENANT_GUID",
  "ClientId": "APPLICATIONID_GUID"
}

For more details, follow this Article

Upvotes: 1

Related Questions