7

I am using Microsoft.ApsNetCore.Cors 2.2

"Access to XMLHttpRequest at 'exampleapi.local' from origin 'example.local' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource."

I set the settings with this:

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

    services.Configure<TokenSettings>(this.Configuration.GetSection("Tokens"));
    services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme)
        .AddJwtBearer(opt =>
        {
            opt.TokenValidationParameters = new TokenValidationParameters
            {
                ValidateIssuer = true,
                ValidateAudience = true,
                ValidateLifetime = true,
                ValidateIssuerSigningKey = true,
                ValidIssuer = Configuration["Tokens:Issuer"],
                ValidAudience = Configuration["Tokens:Audience"],
                IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration["Tokens:SecurityKey"]))
            };
        });

    services.AddMvc();
    services.Configure<LdapConfig>(Configuration.GetSection("ldap"));
    services.AddScoped<ILdapAuthenticationService, LdapAuthenticationService>();
    services.AddScoped<IUserService, UserService>();
    services.AddScoped<IProjectService, ProjectService>();
    services.AddScoped<IProjectMembersService, ProjectMembersService>();
    services.AddScoped<IJourneyUsersService, JourneyUsersService>();
    services.AddScoped<IProjectRolesService, ProjectRolesService>();
    services.AddScoped<IPmoGuardianService, PmoGuardianService>();
    services.AddScoped<IHolidaysService, HolidaysService>();
    services.AddScoped<IMailService, MailService>();
    services.AddScoped<INotificationsService, NotificationsService>();
    services.AddScoped<INotificationUsersService, NotificationUsersService>();
    services.Configure<AWSConfigSes>(Configuration.GetSection("AWSSmtp"));
    services.AddDbContext<JourneyContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("JourneyConnection")));
    services.AddDbContext<TSMContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("TSMConnection")));
    services.AddDbContext<PmoGuardianContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("PmoGuardianConnection")));

}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, IMailService mail, INotificationsService not)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    Recurrence recurrency = Recurrence.GetInstance(not);
    //new TSMClockService(mail);

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

    app.UseMvc();
}

[Produces("application/json")]
[Route("api/Mail")]
[EnableCors("AllowSpecificOrigin")]

But It doesn't work, always I got the same error

8
  • 4
    The CORS headers have to be set by the target server, not your server. They have to give you access, not the other way around. Commented Jan 11, 2019 at 15:43
  • I'm having the exact same issue with 2.2 Commented Jan 11, 2019 at 23:02
  • @Christian did you have any luck figuring this out? Commented Jan 14, 2019 at 15:11
  • Not yet, I will try to do a downgrade to Cors, I hope to resolve the problem with that. And you?? @Capo Commented Jan 14, 2019 at 15:58
  • @ChristianHerrejon - this may be a shot in the dark for you, but I was able to finally get things working by adding <system.webServer> <validation validateIntegratedModeConfiguration="false" />..</system.webServer> to my webconfig on my server. I updated our hosting package for core v2 as well, but this seemed to have no effect. Hopefully this will help! Commented Jan 14, 2019 at 22:00

5 Answers 5

3

I've just lost a couple of minutes trying to figure out why CORS isn't working for requests from http://localhost:8080 that I've setup according to the official documentation.

Well it's because I added a '/' at the end of the URL. So, remove your '/' from the allowed origins.

There's even a Note on the Microsoft docs about this!

Note: The URL must not contain a trailing slash (/). If the URL terminates with /, the comparison returns false and no header is returned.

Sign up to request clarification or add additional context in comments.

Comments

1

Amy's right in her comment. CORS headers need to be set by the target server, not yours.

You will often find issues with CORS if you are trying to hook into an API on a different port but running locally on the same IP address (a most common example is localhost:<> trying to ping localhost<>, etc.).

If you are trying to run this on your local machine with Google chrome you can download the below extension which will allow you to toggle on and off the CORS rule so you can test locally: Allow CORS: Access-Control-Allow-Origin

1 Comment

Thank you. If I am on localhost, the API works fine but if I am on production, the API gets the error
1

This is the exmple provided here:ASP.NET Core 2.2

public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowSpecificOrigin",
                builder => builder.WithOrigins("http://example.com"));
        });
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env, 
        ILoggerFactory loggerFactory)
    {
        loggerFactory.AddConsole();

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

        // Shows UseCors with named policy.
        app.UseCors("AllowSpecificOrigin");

        app.Run(async (context) =>
        {
            await context.Response.WriteAsync("Hello World!");
        });
    }

The finally use it like this on the controller or action:

[EnableCors("AllowSpecificOrigin")]

Also for some reason make sure that app.UseCors is called before app.UseMVC.

Also if all you need is CORS from a single origin; you use simpler solution with no policies:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    app.UseCors(
        options => options.WithOrigins("http://example.com").AllowAnyMethod()
    );

    app.UseMvc();
}

1 Comment

I tried both but It doesn't work, anyway I am grateful
1

Simple and easy way to do it.

  1. Install package

Install-Package Microsoft.AspNetCore.Cors

  1. Put the code below in startup.cs file

app.UseCors(options => options.AllowAnyOrigin());

Comments

1

I know this is an old question but if like me you're using the appsettings.json file for configuration, be sure to add this:

"cors": {
  "rules": [
    {
      "origin": "https://localhost:44379",
      "allow": true
    }
  ]
}

This simple addition made everything magically work for me.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.