Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

CORS not working in Asp.Net Core 3.0 #16672

Closed
martonx opened this issue Oct 30, 2019 · 9 comments
Closed

CORS not working in Asp.Net Core 3.0 #16672

martonx opened this issue Oct 30, 2019 · 9 comments

Comments

@martonx
Copy link

@martonx martonx commented Oct 30, 2019

I want to enable CORS with Asp.Net Core 3.0 API project. This is the basic generated Asp.Net Core Api template. Everything is default from the template, except I added CORS settings from the documentation: Enable Cross-Origin Requests (CORS) in ASP.NET Core

Here it is my Startup.cs

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)
        {
            services.AddControllers();
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                    builder => builder.WithOrigins("localhost", "www.google.com")
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .AllowCredentials());
            });
        }

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors("CorsPolicy");
            app.UseAuthorization();

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

And these are my response headers:
image

What should I set up for getting corret CORS headers in Response?

@BrennanConroy

This comment has been minimized.

Copy link
Contributor

@BrennanConroy BrennanConroy commented Oct 30, 2019

You only get CORS headers for requests to a different domain. So if your site was hosted at localhost:5002 and the web page was provided by a server at localhost:5001.

And the CORS headers will only show up in the OPTIONS request that the browser will make for you when it notices a cross-domain request.

@martonx

This comment has been minimized.

Copy link
Author

@martonx martonx commented Oct 30, 2019

image

Like here? Where should I see CORS headers?

@pranavkm

This comment has been minimized.

Copy link
Contributor

@pranavkm pranavkm commented Oct 30, 2019

@martonx did you update your startup to include the https://www.google.com domain before you made this request?

@martonx

This comment has been minimized.

Copy link
Author

@martonx martonx commented Oct 30, 2019

@pranavkm yes, sorry now I edited original codes with google added.

@martonx

This comment has been minimized.

Copy link
Author

@martonx martonx commented Oct 30, 2019

Oops, I have only one working solution, but at least I found this combination. It seems only app.UseCors (and options inside) can cause real changes in CORS behaviour.

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)
        {
            services.AddControllers();
            services.AddCors();
        }

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

            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(
                options => options.SetIsOriginAllowed(x => _ = true).AllowAnyMethod().AllowAnyHeader().AllowCredentials()
            );

            app.UseAuthorization();

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

This comment has been minimized.

Copy link
Contributor

@mkArtakMSFT mkArtakMSFT commented Oct 31, 2019

Thanks for contacting us. We believe that the question you've raised have been answered. If you still feel a need to continue the discussion, feel free to reopen it and add your comments.

@KamranShahid

This comment has been minimized.

Copy link

@KamranShahid KamranShahid commented Nov 25, 2019

My Class is as following. Please let me know if i have placed usehttpsredirection/usecors correctly or not

public class StartupShutdownHandler
    {

        public static IWebHostBuilder BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args).
            ConfigureKestrel(serverOptions => { }).UseIISIntegration()
            .UseStartup<StartupShutdownHandler>();

        private static readonly ILog Logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
        private const string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";


        public StartupShutdownHandler(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)
        {
            services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
            services.AddControllers(options => options.RespectBrowserAcceptHeader = true).AddXmlSerializerFormatters().AddXmlDataContractSerializerFormatters();//for twilio            
            CorsRelatedPolicyAddition(services);//for Cross origin resource sahring. needed in swagger
        }

        private void CorsRelatedPolicyAddition(IServiceCollection services)
        {
            var lstofCors = ConfigurationHandler.GetSection<List<string>>(StringConstants.AppSettingsKeys.CorsWhitelistedUrl);
            if (lstofCors != null && lstofCors.Count > 0 && lstofCors.Any(h => !string.IsNullOrWhiteSpace(h)))
            {
                services.AddCors(options =>
                {
                    options.AddPolicy(MyAllowSpecificOrigins, builder => { builder.WithOrigins(lstofCors.ToArray()).AllowAnyMethod().AllowAnyHeader(); });
                });

            }
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IHostApplicationLifetime applicationLifetime)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            app.UseRouting();
            app.UseCors(MyAllowSpecificOrigins);
            app.UseHttpsRedirection();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            });
            //app.UseMvc(); //this is changed in 3.0
            applicationLifetime.ApplicationStarted.Register(StartedApplication);
            applicationLifetime.ApplicationStopping.Register(OnShutdown);
        }


        private void OnShutdown()
        {
            ...
        }

        private void StartedApplication()
        {
            .....
        }
    }
@mrunks

This comment has been minimized.

Copy link

@mrunks mrunks commented Dec 2, 2019

I have the same problem where I receive a 401 when I try using CORS in asp.net 3.0.

I am trying to update a 2.1 that was setting dynamic origin and trying to use CORS with Specific Origin hosted by IIS 10 with Windows authentication only fails.

Is there a way to dynamically capture the Origin using Middleware in 3.0 ? I have the following code in a few Production Asp.net 4.x applications that works perfectly fine with Windows Authentication only.

I tried doing something similar with middle ware but still fails. Is there a way to capture the origin dynamically in .NET CORE 3.0 just like one can in a 4.x application hosted with IIS ?

protected void Application_BeginRequest()
{
var currentResponse = HttpContext.Current.Response;

  var currentRequestOrigin = HttpContext.Current.Request.Headers["Origin"];
  if (currentRequestOrigin != null)
  {
    currentResponse.AppendHeader("Access-Control-Allow-Origin", currentRequestOrigin);
  }

if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
  {
    HttpContext.Current.Response.End();
  }

}

@pranavkm

This comment has been minimized.

Copy link
Contributor

@pranavkm pranavkm commented Dec 2, 2019

Hi, it looks like you are posting on a closed issue/PR/commit!

We're very likely to lose track of your bug/feedback/question unless you:

  1. Open a new issue
  2. Explain very clearly what you need help with
  3. If you think you have found a bug, include detailed repro steps so that we can investigate the problem

Thanks!

@dotnet dotnet locked as resolved and limited conversation to collaborators Dec 2, 2019
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
7 participants
You can’t perform that action at this time.