Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow Cors Origin in ASP.NET Core

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

like image 796
Christian Herrejon Avatar asked Jan 11 '19 15:01

Christian Herrejon


Video Answer


3 Answers

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

like image 35
Ben Rinehart Avatar answered Sep 27 '22 16:09

Ben Rinehart


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.

like image 175
milosponj Avatar answered Sep 27 '22 15:09

milosponj


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();
}
like image 43
Jonathan Alfaro Avatar answered Sep 27 '22 17:09

Jonathan Alfaro